"use client"

import { useState } from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { useContactsStore } from "@/lib/contacts/contacts-store"
import { parseBulkContactText } from "@/lib/contacts/import-parsers"
import {
  CONTACTS_MUTED_TEXT,
  CONTACTS_PAGE_LINK_BTN_CLASS,
  CONTACTS_PAGE_TEXTAREA_CLASS,
} from "@/lib/contacts-chrome-classes"
import { cn } from "@/lib/utils"

interface BulkCreateDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onOpenImport?: () => void
}

export function BulkCreateDialog({ open, onOpenChange, onOpenImport }: BulkCreateDialogProps) {
  const [input, setInput] = useState("")
  const addContacts = useContactsStore((s) => s.addContacts)

  function handleCreate() {
    const parsed = parseBulkContactText(input)
    if (parsed.length === 0) return

    addContacts(parsed)
    setInput("")
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Créer plusieurs contacts</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-2">
          <p className={cn("text-sm", CONTACTS_MUTED_TEXT)}>
            Ajoutez des noms, des adresses e-mail ou les deux
          </p>
          <textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Exemples : Andrea Fisher, weaver.blake98@gmail.com, Elisa Beckett <elisa.beckett@gmail.com>"
            className={CONTACTS_PAGE_TEXTAREA_CLASS}
          />
          <p className={cn("text-xs", CONTACTS_MUTED_TEXT)}>
            Vous avez un fichier CSV ou vCard ?{" "}
            <button
              type="button"
              className="cursor-pointer text-primary hover:underline"
              onClick={() => {
                onOpenChange(false)
                onOpenImport?.()
              }}
            >
              Importez les contacts.
            </button>
          </p>
        </div>
        <div className="flex justify-end gap-3">
          <Button variant="ghost" onClick={() => onOpenChange(false)} className={CONTACTS_PAGE_LINK_BTN_CLASS}>
            Non, ne rien faire
          </Button>
          <Button onClick={handleCreate} disabled={!input.trim()} className="text-sm font-medium">
            Créer
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
