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

interface RegulationOption {
    id: number
    code: string
    name: string
    short_name: string | null
}

interface RegulationAppendixFormProps {
    appendix?: RegulationAppendix
    regulationOptions: RegulationOption[]
    onSuccess: () => void
    onCancel: () => void
}

export function RegulationAppendixForm({ appendix, regulationOptions, onSuccess, onCancel }: RegulationAppendixFormProps) {
    const { data, setData, post, put, transform, processing, errors } = useForm({
        regulation_id: String(appendix?.regulation_id ?? ''),
        name: appendix?.name ?? '',
        sort_order: String(appendix?.sort_order ?? 0),
        description: appendix?.description ?? '',
        is_active: appendix?.is_active ?? true,
    })

    function submit(e: React.FormEvent) {
        e.preventDefault()

        transform((formData) => ({
            ...formData,
            regulation_id: Number(formData.regulation_id),
            sort_order: formData.sort_order ? Number(formData.sort_order) : 0,
        }))

        if (appendix) {
            put(`/master-data/regulation-appendices/${appendix.id}`, {
                onSuccess: () => {
                    toast.success('Lampiran regulasi berhasil diperbarui.')
                    onSuccess()
                },
                onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Terjadi kesalahan.'),
            })
            return
        }

        post('/master-data/regulation-appendices', {
            onSuccess: () => {
                toast.success('Lampiran regulasi berhasil ditambahkan.')
                onSuccess()
            },
            onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Terjadi kesalahan.'),
        })
    }

    return (
        <form onSubmit={submit} className='space-y-4'>
            <div className='grid grid-cols-1 gap-4 sm:grid-cols-2'>
                <div className='col-span-full space-y-1.5'>
                    <Label htmlFor='appendix-regulation'>
                        Regulasi <span className='text-destructive'>*</span>
                    </Label>
                    <ComboboxDropdown
                        value={data.regulation_id || undefined}
                        onValueChange={(value) => setData('regulation_id', value ?? '')}
                        placeholder='Pilih regulasi...'
                        options={regulationOptions.map((option) => ({
                            value: String(option.id),
                            label: option.short_name
                                ? `${option.short_name} - ${option.name}`
                                : `${option.code} - ${option.name}`,
                        }))}
                        searchPlaceholder='Cari regulasi...'
                        emptyText='Regulasi tidak ditemukan.'
                    />
                    {errors.regulation_id && <p className='text-xs text-destructive'>{errors.regulation_id}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='appendix-name'>
                        Nama Lampiran <span className='text-destructive'>*</span>
                    </Label>
                    <Input
                        id='appendix-name'
                        value={data.name}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('name', e.target.value)}
                        placeholder='e.g. Baku Mutu Air Limbah'
                    />
                    {errors.name && <p className='text-xs text-destructive'>{errors.name}</p>}
                </div>


                <div className='space-y-1.5'>
                    <Label htmlFor='appendix-sort'>Urutan</Label>
                    <Input
                        id='appendix-sort'
                        type='number'
                        min='0'
                        value={data.sort_order}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('sort_order', e.target.value)}
                        placeholder='0'
                    />
                    {errors.sort_order && <p className='text-xs text-destructive'>{errors.sort_order}</p>}
                </div>

                <div className='col-span-full space-y-1.5'>
                    <Label htmlFor='appendix-description'>Deskripsi</Label>
                    <Textarea
                        id='appendix-description'
                        rows={3}
                        value={data.description}
                        onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setData('description', e.target.value)}
                        placeholder='Deskripsi singkat lampiran regulasi...'
                    />
                    {errors.description && <p className='text-xs text-destructive'>{errors.description}</p>}
                </div>

                <div className='col-span-full flex items-center gap-2'>
                    <Checkbox
                        id='appendix-active'
                        checked={data.is_active}
                        onCheckedChange={(value: boolean | 'indeterminate') => setData('is_active', !!value)}
                    />
                    <Label htmlFor='appendix-active' className='cursor-pointer font-normal'>
                        Lampiran aktif
                    </Label>
                </div>
            </div>

            <div className='flex justify-end gap-2 pt-2'>
                <Button type='button' variant='outline' onClick={onCancel} disabled={processing}>
                    Batal
                </Button>
                <Button type='submit' disabled={processing}>
                    {processing ? 'Menyimpan...' : appendix ? 'Simpan Perubahan' : 'Simpan'}
                </Button>
            </div>
        </form>
    )
}
