import { useForm } from '@inertiajs/react'
import { Trash2, Plus } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@ui/components/ui/button'
import { Input } from '@ui/components/ui/input'
import { Label } from '@ui/components/ui/label'
import { Checkbox } from '@ui/components/ui/checkbox'
import { Textarea } from '@ui/components/ui/textarea'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'

interface ReagentItemOption {
    id: number
    name: string
    brand?: string | null
    unit?: string | null
    label: string
}

interface ReagentMasterItemInput {
    id?: number
    item_id: number
    qty: number
    unit: string
    notes: string
}

interface ReagentMaster {
    id: number
    code: string
    name: string
    description?: string | null
    is_active: boolean
    items?: Array<{
        id?: number
        item_id: number
        qty: number
        unit?: string | null
        notes?: string | null
        item?: { id: number; unit?: string | null }
    }>
}

interface Props {
    item?: ReagentMaster
    reagentItemOptions: ReagentItemOption[]
    onSuccess: () => void
    onCancel: () => void
    onDelete: (item: ReagentMaster) => void
}

export function ReagentMasterForm({ item, reagentItemOptions, onSuccess, onCancel, onDelete }: Props) {
    const unitOptions = Array.from(
        new Set(
            reagentItemOptions
                .map((option) => option.unit?.trim())
                .filter((unit): unit is string => Boolean(unit))
        )
    ).map((unit) => ({ value: unit, label: unit }))

    const defaultRows: ReagentMasterItemInput[] = item?.items?.length
        ? item.items.map((row) => ({
            id: row.id,
            item_id: row.item_id,
            qty: Number(row.qty || 0),
            unit: row.unit ?? row.item?.unit ?? '',
            notes: row.notes ?? '',
        }))
        : [{ item_id: 0, qty: 0, unit: '', notes: '' }]

    const { data, setData, post, put, processing, errors } = useForm({
        code: item?.code ?? '',
        name: item?.name ?? '',
        description: item?.description ?? '',
        is_active: item?.is_active ?? true,
        items: defaultRows,
    })

    function updateRow(index: number, patch: Partial<ReagentMasterItemInput>) {
        setData('items', data.items.map((row, i) => (i === index ? { ...row, ...patch } : row)))
    }

    function addRow() {
        setData('items', [...data.items, { item_id: 0, qty: 0, unit: '', notes: '' }])
    }

    function removeRow(index: number) {
        if (data.items.length <= 1) return
        setData('items', data.items.filter((_, i) => i !== index))
    }

    function submit(e: React.FormEvent) {
        e.preventDefault()
        const path = item ? `/master-data/reagent-masters/${item.id}` : '/master-data/reagent-masters'
        const method = item ? put : post

        method(path, {
            data: { ...data, code: data.code.toUpperCase() },
            onSuccess: () => {
                toast.success(item ? 'Master reagen diperbarui.' : 'Master reagen ditambahkan.')
                onSuccess()
            },
            onError: (bag) => toast.error(Object.values(bag)[0] ?? 'Terjadi kesalahan.'),
        })
    }

    return (
        <form onSubmit={submit} className='space-y-4'>
            <div className='space-y-1.5'>
                <Label>Kode</Label>
                <p className='text-xs text-muted-foreground'>Opsional. Jika dikosongkan, sistem generate otomatis.</p>
                <Input value={data.code} onChange={(e) => setData('code', e.target.value.toUpperCase())} />
                {errors.code && <p className='text-xs text-destructive'>{errors.code}</p>}
            </div>

            <div className='space-y-1.5'>
                <Label>Nama Reagen Campuran</Label>
                <Input value={data.name} onChange={(e) => setData('name', e.target.value)} />
                {errors.name && <p className='text-xs text-destructive'>{errors.name}</p>}
            </div>

            <div className='space-y-1.5'>
                <Label>Deskripsi</Label>
                <Textarea value={data.description} onChange={(e) => setData('description', e.target.value)} rows={3} />
                {errors.description && <p className='text-xs text-destructive'>{errors.description}</p>}
            </div>

            <div className='space-y-2 rounded-lg border p-3'>
                <div className='flex items-center justify-between'>
                    <Label>Komposisi Item Reagen</Label>
                    <Button type='button' variant='outline' size='sm' className='gap-1' onClick={addRow}>
                        <Plus className='h-3.5 w-3.5' /> Tambah Baris
                    </Button>
                </div>

                {data.items.map((row, index) => (
                    <div key={row.id ?? `new-${index}`} className='grid grid-cols-12 items-start gap-2 rounded-md border p-2'>
                        <div className='col-span-12 md:col-span-4'>
                            <Label className='text-xs'>Item Bahan/Reagen</Label>
                            <div className='mt-1'>
                                <ComboboxDropdown
                                    value={row.item_id ? String(row.item_id) : undefined}
                                    onValueChange={(value) => {
                                        const itemId = value ? Number(value) : 0
                                        const selected = reagentItemOptions.find((opt) => opt.id === itemId)
                                        updateRow(index, { item_id: itemId, unit: row.unit || selected?.unit || '' })
                                    }}
                                    placeholder='Pilih item...'
                                    searchPlaceholder='Cari item reagen...'
                                    emptyText='Item tidak ditemukan.'
                                    options={reagentItemOptions.map((opt) => ({
                                        value: String(opt.id),
                                        label: opt.label,
                                    }))}
                                />
                            </div>
                            {errors[`items.${index}.item_id` as keyof typeof errors] && <p className='mt-1 text-xs text-destructive'>{errors[`items.${index}.item_id` as keyof typeof errors] as string}</p>}
                        </div>

                        <div className='col-span-6 md:col-span-2'>
                            <Label className='text-xs'>Qty</Label>
                            <Input type='number' min={0} step='0.0001' value={row.qty} onChange={(e) => updateRow(index, { qty: Number(e.target.value || 0) })} className='mt-1' />
                            {errors[`items.${index}.qty` as keyof typeof errors] && <p className='mt-1 text-xs text-destructive'>{errors[`items.${index}.qty` as keyof typeof errors] as string}</p>}
                        </div>

                        <div className='col-span-6 md:col-span-2'>
                            <Label className='text-xs'>Satuan</Label>
                            <div className='mt-1'>
                                <ComboboxDropdown
                                    value={row.unit || undefined}
                                    onValueChange={(value) => updateRow(index, { unit: value ?? '' })}
                                    placeholder='Pilih satuan...'
                                    searchPlaceholder='Cari satuan...'
                                    emptyText='Satuan tidak ditemukan.'
                                    options={unitOptions}
                                />
                            </div>
                        </div>

                        <div className='col-span-10 md:col-span-3'>
                            <Label className='text-xs'>Catatan</Label>
                            <Textarea value={row.notes} onChange={(e) => updateRow(index, { notes: e.target.value })} className='mt-1 min-h-[64px]' />
                        </div>

                        <div className='col-span-2 md:col-span-1 flex justify-end pt-6'>
                            <Button type='button' variant='ghost' size='icon' className='h-9 w-9' onClick={() => removeRow(index)} disabled={data.items.length <= 1}>
                                <Trash2 className='h-4 w-4 text-rose-600' />
                            </Button>
                        </div>
                    </div>
                ))}

                {errors.items && <p className='text-xs text-destructive'>{errors.items}</p>}
            </div>

            <div className='flex items-center gap-2'>
                <Checkbox checked={data.is_active} onCheckedChange={(v) => setData('is_active', !!v)} id='rm-active' />
                <Label htmlFor='rm-active' className='cursor-pointer font-normal'>Aktif</Label>
            </div>

            <div className='flex justify-between gap-2'>
                <div>
                    {item && (
                        <Button type='button' variant='destructive' onClick={() => onDelete(item)} disabled={processing}>
                            Hapus
                        </Button>
                    )}
                </div>
                <div className='flex gap-2'>
                    <Button type='button' variant='outline' onClick={onCancel} disabled={processing}>Batal</Button>
                    <Button type='submit' disabled={processing}>{processing ? 'Menyimpan...' : 'Simpan'}</Button>
                </div>
            </div>
        </form>
    )
}
