"use client"

import { useState } from "react"
import { toast } from "sonner"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Combobox } from "@/components/ui/combobox"
import type { Payee, Category } from "@/lib/airtable"

interface CreatePayeeDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  categories: Category[]
  onPayeeCreated: (payee: Payee) => void
}

export function CreatePayeeDialog({
  open,
  onOpenChange,
  categories,
  onPayeeCreated,
}: CreatePayeeDialogProps) {
  const [name, setName] = useState("")
  const [notes, setNotes] = useState("")
  const [defaultCategory, setDefaultCategory] = useState("")
  const [isCreating, setIsCreating] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!name.trim()) {
      toast.error("Payee name is required")
      return
    }

    setIsCreating(true)

    try {
      const payeeData: any = { name: name.trim() }
      if (notes.trim()) payeeData.notes = notes.trim()
      if (defaultCategory) payeeData.defaultCategoryId = defaultCategory

      const response = await fetch("/api/payees", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payeeData),
      })

      if (!response.ok) {
        throw new Error("Failed to create payee")
      }

      const newPayee = await response.json()

      toast.success(`Payee "${newPayee.name}" created successfully!`)
      onPayeeCreated(newPayee)

      // Reset form
      setName("")
      setNotes("")
      setDefaultCategory("")
    } catch (error) {
      console.error("Error creating payee:", error)
      toast.error("Failed to create payee")
    } finally {
      setIsCreating(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New Payee</DialogTitle>
          <DialogDescription>
            Add a new payee to your expense tracking system.
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label htmlFor="payee-name">
              Payee Name <span className="text-red-500">*</span>
            </Label>
            <Input
              id="payee-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Enter payee name"
              required
            />
          </div>

          <div>
            <Label htmlFor="payee-notes">Notes (Optional)</Label>
            <Textarea
              id="payee-notes"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="Add any notes about this payee"
              rows={3}
            />
          </div>

          <div>
            <Label>Default Category (Optional)</Label>
            <Combobox
              options={categories.map((c) => ({ value: c.id!, label: c.name }))}
              value={defaultCategory}
              onValueChange={setDefaultCategory}
              placeholder="Select default category..."
              searchPlaceholder="Search categories..."
              emptyText="No category found."
            />
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isCreating}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isCreating}>
              {isCreating ? "Creating..." : "Create Payee"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
