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 { FileDropzoneField } from '@/components/common/FileDropzoneField'
import { type RegulationAttachment } from '@/types/glims'

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

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

interface RegulationAttachmentFormProps {
    attachment?: RegulationAttachment
    regulationOptions: RegulationOption[]
    sampleTypeOptions: SampleTypeOption[]
    onSuccess: () => void
    onCancel: () => void
}

export function RegulationAttachmentForm({
    attachment,
    regulationOptions,
    sampleTypeOptions,
    onSuccess,
    onCancel,
}: RegulationAttachmentFormProps) {
    const { data, setData, post, put, transform, processing, errors } = useForm({
        regulation_id: String(attachment?.regulation_id ?? ''),
        sample_type_id: String(attachment?.sample_type_id ?? ''),
        class_name: attachment?.class_name ?? '',
        name: attachment?.name ?? '',
        category: attachment?.category ?? '',
        description: attachment?.description ?? '',
        is_active: attachment?.is_active ?? true,
        file: null as File | null,
    })

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

        transform((formData) => ({
            ...formData,
            regulation_id: Number(formData.regulation_id),
            sample_type_id: formData.sample_type_id ? Number(formData.sample_type_id) : null,
        }))

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

        post('/master-data/regulation-attachments', {
            forceFormData: true,
            onSuccess: () => {
                toast.success('Attachment 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='attachment-regulation'>
                        Regulasi <span className='text-destructive'>*</span>
                    </Label>
                    <select
                        id='attachment-regulation'
                        value={data.regulation_id}
                        onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setData('regulation_id', e.target.value)}
                        className='w-full rounded-md border bg-background px-3 py-2 text-sm'
                    >
                        <option value=''>Pilih regulasi...</option>
                        {regulationOptions.map((option) => (
                            <option key={option.id} value={option.id}>
                                {option.short_name
                                    ? `${option.short_name} - ${option.name}`
                                    : `${option.code} - ${option.name}`}
                            </option>
                        ))}
                    </select>
                    {errors.regulation_id && <p className='text-xs text-destructive'>{errors.regulation_id}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='attachment-sample-type'>Jenis Sampel</Label>
                    <ComboboxDropdown
                        value={data.sample_type_id || undefined}
                        onValueChange={(value) => setData('sample_type_id', value ?? '')}
                        placeholder='Semua Jenis Sampel'
                        options={sampleTypeOptions.map((option) => ({
                            value: String(option.id),
                            label: `${option.code} - ${option.name}`,
                        }))}
                        searchPlaceholder='Cari jenis sampel...'
                        emptyText='Jenis sampel 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 htmlFor='attachment-class'>Kelas Dokumen</Label>
                    <Input
                        id='attachment-class'
                        value={data.class_name}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('class_name', e.target.value)}
                        placeholder='e.g. Dokumen Utama, Lampiran I'
                    />
                    {errors.class_name && <p className='text-xs text-destructive'>{errors.class_name}</p>}
                </div>

                <div className='col-span-full space-y-1.5'>
                    <Label htmlFor='attachment-name'>
                        Nama Dokumen <span className='text-destructive'>*</span>
                    </Label>
                    <Input
                        id='attachment-name'
                        value={data.name}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('name', e.target.value)}
                        placeholder='Nama dokumen untuk ditampilkan di daftar'
                    />
                    {errors.name && <p className='text-xs text-destructive'>{errors.name}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='attachment-category'>Kategori</Label>
                    <Input
                        id='attachment-category'
                        value={data.category}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('category', e.target.value)}
                        placeholder='e.g. Baku Mutu, Acuan, SK'
                    />
                    {errors.category && <p className='text-xs text-destructive'>{errors.category}</p>}
                </div>

                <div className='col-span-full space-y-1.5'>
                    <FileDropzoneField
                        id='attachment-file'
                        label={attachment ? 'File (opsional untuk ganti file)' : 'File'}
                        required={!attachment}
                        accept='.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png'
                        file={data.file}
                        existingFileName={attachment?.file_name}
                        helperText='Format: PDF, DOC(X), XLS(X), JPG, PNG'
                        error={errors.file}
                        onChange={(file) => setData('file', file)}
                    />
                </div>

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

                <div className='col-span-full flex items-center gap-2'>
                    <Checkbox
                        id='attachment-active'
                        checked={data.is_active}
                        onCheckedChange={(value: boolean | 'indeterminate') => setData('is_active', !!value)}
                    />
                    <Label htmlFor='attachment-active' className='cursor-pointer font-normal'>
                        Attachment 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...' : attachment ? 'Simpan Perubahan' : 'Simpan'}
                </Button>
            </div>
        </form>
    )
}
