import { useForm } from '@inertiajs/react'
import { useMemo } from '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 { ComboboxDropdown } from '@ui/components/combobox-dropdown'

interface UnitItem {
    id: number
    name: string
    unit_type: string
    is_active: boolean
}

interface Props {
    item?: UnitItem
    unitTypeOptions: string[]
    onSuccess: () => void
    onCancel: () => void
}

export function UnitForm({ item, unitTypeOptions, onSuccess, onCancel }: Props) {
    const normalizedTypeOptions = useMemo(
        () => unitTypeOptions.filter((type) => type.trim() !== ''),
        [unitTypeOptions]
    )

    const { data, setData, post, put, processing, errors } = useForm({
        name: item?.name ?? '',
        unit_type: item?.unit_type ?? 'ANALISIS',
        is_active: item?.is_active ?? true,
    })

    function submit(e: React.FormEvent) {
        e.preventDefault()
        const path = item ? `/master-data/units/${item.id}` : '/master-data/units'
        const method = item ? put : post
        const payload = {
            ...data,
            unit_type: data.unit_type.trim().toUpperCase(),
        }
        method(path, {
            data: payload,
            onSuccess: () => { toast.success(item ? 'Satuan diperbarui.' : 'Satuan ditambahkan.'); onSuccess() },
            onError: (bag) => toast.error(Object.values(bag)[0] ?? 'Terjadi kesalahan.'),
        })
    }

    return (
        <form onSubmit={submit} className='space-y-4'>
            <div className='grid grid-cols-1 gap-4'>
                <div className='space-y-1.5'>
                    <Label>Nama Satuan</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>Jenis Satuan</Label>
                    <p className='text-xs text-muted-foreground'>
                        Pilih jenis satuan dari daftar.
                    </p>
                    <ComboboxDropdown
                        value={data.unit_type || undefined}
                        onValueChange={(value) => setData('unit_type', value ?? '')}
                        placeholder='Pilih jenis satuan...'
                        options={normalizedTypeOptions.map((type) => ({ value: type, label: type }))}
                        searchPlaceholder='Cari jenis satuan...'
                        emptyText='Jenis satuan tidak ditemukan.'
                        className='w-full'
                    />
                    {errors.unit_type && <p className='text-xs text-destructive'>{errors.unit_type}</p>}
                </div>
                <div className='flex items-center gap-2'>
                    <Checkbox checked={data.is_active} onCheckedChange={(v) => setData('is_active', !!v)} id='u-active' />
                    <Label htmlFor='u-active' className='cursor-pointer font-normal'>Aktif</Label>
                </div>
            </div>
            <div className='flex justify-end gap-2'>
                <Button type='button' variant='outline' onClick={onCancel} disabled={processing}>Batal</Button>
                <Button type='submit' disabled={processing}>{processing ? 'Menyimpan...' : 'Simpan'}</Button>
            </div>
        </form>
    )
}
