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 { Product } from '@/types/inventory'

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

export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
  const { data: allCats } = useQuery(categoryAllOptions())
  const categories = (allCats?.data ?? []).filter((c) => c.isActive)

  const { register, handleSubmit, setValue, watch } = useForm({
    defaultValues: {
      name: defaultValues?.name ?? '',
      sku: defaultValues?.sku ?? '',
      upc: defaultValues?.upc ?? '',
      brand: defaultValues?.brand ?? '',
      model: defaultValues?.model ?? '',
      description: defaultValues?.description ?? '',
      categoryId: defaultValues?.categoryId ?? '',
      price: defaultValues?.price ?? '',
      minPrice: defaultValues?.minPrice ?? '',
      rentalRateMonthly: defaultValues?.rentalRateMonthly ?? '',
      qtyOnHand: defaultValues?.qtyOnHand ?? 0,
      qtyReorderPoint: defaultValues?.qtyReorderPoint ?? '',
      isSerialized: defaultValues?.isSerialized ?? false,
      isRental: defaultValues?.isRental ?? false,
      isDualUseRepair: defaultValues?.isDualUseRepair ?? false,
      isConsumable: defaultValues?.isConsumable ?? false,
      isActive: defaultValues?.isActive ?? true,
    },
  })

  const categoryId = watch('categoryId')
  const isRental = watch('isRental')
  const isSerialized = watch('isSerialized')
  const isDualUseRepair = watch('isDualUseRepair')
  const isConsumable = watch('isConsumable')
  const isActive = watch('isActive')

  function handleFormSubmit(data: Record<string, unknown>) {
    onSubmit({
      name: data.name,
      sku: (data.sku as string) || undefined,
      upc: (data.upc as string) || undefined,
      brand: (data.brand as string) || undefined,
      model: (data.model as string) || undefined,
      description: (data.description as string) || undefined,
      categoryId: (data.categoryId as string) || undefined,
      price: (data.price as string) ? Number(data.price) : undefined,
      minPrice: (data.minPrice as string) ? Number(data.minPrice) : undefined,
      rentalRateMonthly: isRental && (data.rentalRateMonthly as string) ? Number(data.rentalRateMonthly) : undefined,
      qtyOnHand: Number(data.qtyOnHand),
      qtyReorderPoint: (data.qtyReorderPoint as string) ? Number(data.qtyReorderPoint) : undefined,
      isSerialized: data.isSerialized,
      isRental: data.isRental,
      isDualUseRepair: data.isDualUseRepair,
      isConsumable: data.isConsumable,
      isActive: data.isActive,
    })
  }

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="p-name">Name *</Label>
        <Input id="p-name" {...register('name')} placeholder="e.g. Fender Player Stratocaster" required />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="p-sku">SKU</Label>
          <Input id="p-sku" {...register('sku')} placeholder="STR-001" />
        </div>
        <div className="space-y-2">
          <Label htmlFor="p-upc">UPC / Barcode</Label>
          <Input id="p-upc" {...register('upc')} placeholder="0123456789" />
        </div>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="p-brand">Brand</Label>
          <Input id="p-brand" {...register('brand')} placeholder="Fender" />
        </div>
        <div className="space-y-2">
          <Label htmlFor="p-model">Model</Label>
          <Input id="p-model" {...register('model')} placeholder="Player Stratocaster" />
        </div>
      </div>
      <div className="space-y-2">
        <Label>Category</Label>
        <Select value={categoryId || 'none'} onValueChange={(v) => setValue('categoryId', v === 'none' ? '' : v)}>
          <SelectTrigger>
            <SelectValue placeholder="Select category..." />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="none">No Category</SelectItem>
            {categories.map((c) => (
              <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="grid grid-cols-3 gap-4">
        <div className="space-y-2">
          <Label htmlFor="p-price">Price</Label>
          <Input id="p-price" type="number" step="0.01" min="0" {...register('price')} placeholder="0.00" />
        </div>
        <div className="space-y-2">
          <Label htmlFor="p-min-price">Min Price</Label>
          <Input id="p-min-price" type="number" step="0.01" min="0" {...register('minPrice')} placeholder="0.00" />
        </div>
        {isRental && (
          <div className="space-y-2">
            <Label htmlFor="p-rental-rate">Rental / Month</Label>
            <Input id="p-rental-rate" type="number" step="0.01" min="0" {...register('rentalRateMonthly')} placeholder="0.00" />
          </div>
        )}
      </div>
      {!isSerialized && (
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="p-qty">Qty On Hand</Label>
            <Input id="p-qty" type="number" min="0" {...register('qtyOnHand')} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="p-reorder">Reorder Point</Label>
            <Input id="p-reorder" type="number" min="0" {...register('qtyReorderPoint')} placeholder="—" />
          </div>
        </div>
      )}
      <div className="space-y-2">
        <Label htmlFor="p-desc">Description</Label>
        <textarea
          id="p-desc"
          {...register('description')}
          rows={3}
          placeholder="Product description..."
          className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring resize-none"
        />
      </div>
      <div className="space-y-2">
        <Label className="text-sm font-medium">Options</Label>
        <div className="flex flex-wrap gap-4">
          <label className="flex items-center gap-2 text-sm cursor-pointer">
            <input type="checkbox" checked={isSerialized} onChange={(e) => setValue('isSerialized', e.target.checked)} className="h-4 w-4" />
            Serialized (track individual units)
          </label>
          <label className="flex items-center gap-2 text-sm cursor-pointer">
            <input type="checkbox" checked={isRental} onChange={(e) => setValue('isRental', e.target.checked)} className="h-4 w-4" />
            Available for Rental
          </label>
          <label className="flex items-center gap-2 text-sm cursor-pointer">
            <input type="checkbox" checked={isDualUseRepair} onChange={(e) => setValue('isDualUseRepair', e.target.checked)} className="h-4 w-4" />
            Available as Repair Line Item
          </label>
          <label className="flex items-center gap-2 text-sm cursor-pointer">
            <input type="checkbox" checked={isConsumable} onChange={(e) => setValue('isConsumable', e.target.checked)} className="h-4 w-4" />
            Consumable (internal use, not sold at POS)
          </label>
          <label className="flex items-center gap-2 text-sm cursor-pointer">
            <input type="checkbox" checked={isActive} onChange={(e) => setValue('isActive', e.target.checked)} className="h-4 w-4" />
            Active
          </label>
        </div>
      </div>
      <Button type="submit" disabled={loading} className="w-full">
        {loading ? 'Saving...' : defaultValues?.id ? 'Save Changes' : 'Create Product'}
      </Button>
    </form>
  )
}
