"use client"

import { useState } from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { parseBulkContactText } from "@/lib/contacts/import-parsers"
import { useCreateContact } from "@/lib/api/hooks/use-contact-mutations"
import { fullContactToApiContact } from "@/lib/api/adapters"
import { useContactsList } from "@/lib/contacts/use-contacts-list"
import type { FullContact } from "@/lib/contacts/types"
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 createContactMutation = useCreateContact()
  const { bookId } = useContactsList()

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

    for (const partial of parsed) {
      const fullContact: FullContact = {
        id: crypto.randomUUID(),
        createdAt: Date.now(),
        updatedAt: Date.now(),
        ...partial,
        firstName: partial.firstName ?? "",
        lastName: partial.lastName ?? "",
        emails: partial.emails ?? [],
        phones: partial.phones ?? [],
      }
      createContactMutation.mutate({
        bookId,
        contact: fullContactToApiContact(fullContact),
      })
    }
    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>
  )
}
