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

interface Option {
    id: number
    code: string
    name: string
}

interface PlottingItem {
    id: number
    sample_type_id: number
    gwin_item_category_id: number
    qty: number
    notes?: string | null
    is_active: boolean
}

interface Props {
    item?: PlottingItem
    sampleTypeOptions: Option[]
    samplingToolGroupOptions: Option[]
    initialSampleTypeId?: number | null
    onSuccess: () => void
    onCancel: () => void
}

export function SamplingToolPlottingForm({
    item,
    sampleTypeOptions,
    samplingToolGroupOptions,
    initialSampleTypeId,
    onSuccess,
    onCancel,
}: Props) {
    const { data, setData, post, put, transform, processing, errors } = useForm({
        sample_type_id: item?.sample_type_id
            ? String(item.sample_type_id)
            : (initialSampleTypeId ? String(initialSampleTypeId) : ''),
        gwin_item_category_id: item?.gwin_item_category_id ? String(item.gwin_item_category_id) : '',
        qty: String(item?.qty ?? 1),
        notes: item?.notes ?? '',
        is_active: item?.is_active ?? true,
    })

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

        transform(() => ({
            sample_type_id: Number(data.sample_type_id),
            gwin_item_category_id: Number(data.gwin_item_category_id),
            qty: Number(data.qty),
            notes: data.notes || null,
            is_active: data.is_active,
        }))

        method(path, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(item ? 'Plotting alat sampling diperbarui.' : 'Plotting alat sampling 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>Sample Type</Label>
                <ComboboxDropdown
                    value={data.sample_type_id || undefined}
                    onValueChange={(value) => setData('sample_type_id', value ?? '')}
                    placeholder='Pilih sample type...'
                    options={sampleTypeOptions.map((o) => ({ value: String(o.id), label: `${o.code} - ${o.name}` }))}
                    searchPlaceholder='Cari sample type...'
                    emptyText='Sample type tidak ditemukan.'
                />
                {errors.sample_type_id && <p className='text-xs text-destructive'>{errors.sample_type_id}</p>}
            </div>
            <div className='space-y-1.5'>
                <Label>Group Alat</Label>
                <ComboboxDropdown
                    value={data.gwin_item_category_id || undefined}
                    onValueChange={(value) => setData('gwin_item_category_id', value ?? '')}
                    placeholder='Pilih group alat...'
                    options={samplingToolGroupOptions.map((o) => ({ value: String(o.id), label: `${o.code} - ${o.name}` }))}
                    searchPlaceholder='Cari group alat...'
                    emptyText='Group alat tidak ditemukan.'
                />
                {errors.gwin_item_category_id && <p className='text-xs text-destructive'>{errors.gwin_item_category_id}</p>}
            </div>
            <div className='space-y-1.5'>
                <Label>Qty</Label>
                <Input type='number' min='0.01' step='0.01' value={data.qty} onChange={(e) => setData('qty', e.target.value)} />
                {errors.qty && <p className='text-xs text-destructive'>{errors.qty}</p>}
            </div>
            <div className='space-y-1.5'>
                <Label>Catatan</Label>
                <Textarea value={data.notes} onChange={(e) => setData('notes', e.target.value)} rows={3} />
                {errors.notes && <p className='text-xs text-destructive'>{errors.notes}</p>}
            </div>
            <div className='flex items-center gap-2'>
                <Checkbox checked={data.is_active} onCheckedChange={(v) => setData('is_active', !!v)} id='stp-active' />
                <Label htmlFor='stp-active' className='cursor-pointer font-normal'>Aktif</Label>
            </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>
    )
}
