import { useForm } from 'react-hook-form'
import { useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { categoryAllOptions } from '@/api/inventory'
import type { Category } from '@/types/inventory'

interface Props {
  defaultValues?: Partial<Category>
  onSubmit: (data: Record<string, unknown>) => void
  onDelete?: () => void
  loading?: boolean
  deleteLoading?: boolean
}

export function CategoryForm({ defaultValues, onSubmit, onDelete, loading, deleteLoading }: Props) {
  const { data: allCats } = useQuery(categoryAllOptions())
  const categories = (allCats?.data ?? []).filter((c) => c.id !== defaultValues?.id && c.isActive)

  const { register, handleSubmit, setValue, watch } = useForm({
    defaultValues: {
      name: defaultValues?.name ?? '',
      parentId: defaultValues?.parentId ?? '',
      sortOrder: defaultValues?.sortOrder ?? 0,
      isActive: defaultValues?.isActive ?? true,
    },
  })

  const parentId = watch('parentId')
  const isActive = watch('isActive')

  function handleFormSubmit(data: { name: string; parentId: string; sortOrder: number; isActive: boolean }) {
    onSubmit({
      name: data.name,
      parentId: data.parentId || undefined,
      sortOrder: Number(data.sortOrder),
      isActive: data.isActive,
    })
  }

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="cat-name">Name *</Label>
        <Input id="cat-name" {...register('name')} placeholder="e.g. Guitars, Accessories" required />
      </div>
      <div className="space-y-2">
        <Label>Parent Category</Label>
        <Select value={parentId || 'none'} onValueChange={(v) => setValue('parentId', v === 'none' ? '' : v)}>
          <SelectTrigger>
            <SelectValue placeholder="None (Top Level)" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="none">None (Top Level)</SelectItem>
            {categories.map((c) => (
              <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="cat-order">Sort Order</Label>
          <Input id="cat-order" type="number" min={0} {...register('sortOrder')} />
        </div>
        <div className="flex items-center gap-2 pt-7">
          <input
            id="cat-active"
            type="checkbox"
            checked={isActive}
            onChange={(e) => setValue('isActive', e.target.checked)}
            className="h-4 w-4"
          />
          <Label htmlFor="cat-active">Active</Label>
        </div>
      </div>
      <div className="flex gap-2 pt-2">
        <Button type="submit" disabled={loading} className="flex-1">
          {loading ? 'Saving...' : defaultValues?.id ? 'Save Changes' : 'Create Category'}
        </Button>
        {onDelete && (
          <Button type="button" variant="destructive" disabled={deleteLoading} onClick={onDelete}>
            {deleteLoading ? 'Deleting...' : 'Delete'}
          </Button>
        )}
      </div>
    </form>
  )
}
