import { useMemo } from 'react'
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 { type TestTemplate } from '@/types/glims'

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

interface RegulationOption extends OptionSimple {
    short_name?: string | null
}

interface AppendixOption extends OptionSimple {
    regulation_id: number
    appendix_number?: string | null
}

interface TestTemplateFormProps {
    testTemplate?: TestTemplate
    sampleTypeOptions: OptionSimple[]
    regulationOptions: RegulationOption[]
    appendixOptions: AppendixOption[]
    onSuccess: () => void
    onCancel: () => void
}

export function TestTemplateForm({
    testTemplate,
    sampleTypeOptions,
    regulationOptions,
    appendixOptions,
    onSuccess,
    onCancel,
}: TestTemplateFormProps) {
    const { data, setData, post, put, transform, processing, errors } = useForm({
        sample_type_id: String(testTemplate?.sample_type_id ?? ''),
        regulation_id: testTemplate?.regulation_id ? String(testTemplate.regulation_id) : '',
        regulation_appendix_id: testTemplate?.regulation_appendix_id ? String(testTemplate.regulation_appendix_id) : '',
        code: testTemplate?.code ?? '',
        name: testTemplate?.name ?? '',
        effective_date: testTemplate?.effective_date ?? '',
        description: testTemplate?.description ?? '',
        is_active: testTemplate?.is_active ?? true,
    })

    const filteredAppendixOptions = useMemo(() => (
        data.regulation_id
            ? appendixOptions.filter((item) => String(item.regulation_id) === String(data.regulation_id))
            : appendixOptions
    ), [appendixOptions, data.regulation_id])

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

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

        if (testTemplate) {
            put(`/master-data/test-templates/${testTemplate.id}`, {
                onSuccess: () => {
                    toast.success('Template uji berhasil diperbarui.')
                    onSuccess()
                },
                onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Terjadi kesalahan.'),
            })
            return
        }

        post('/master-data/test-templates', {
            onSuccess: () => {
                toast.success('Template uji 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='space-y-1.5'>
                    <Label htmlFor='tt-sample-type'>
                        Jenis Sampel <span className='text-destructive'>*</span>
                    </Label>
                    <select
                        id='tt-sample-type'
                        value={data.sample_type_id}
                        onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setData('sample_type_id', e.target.value)}
                        className='w-full rounded-md border bg-background px-3 py-2 text-sm'
                    >
                        <option value=''>Pilih jenis sampel...</option>
                        {sampleTypeOptions.map((option) => (
                            <option key={option.id} value={option.id}>{option.code} - {option.name}</option>
                        ))}
                    </select>
                    {errors.sample_type_id && <p className='text-xs text-destructive'>{errors.sample_type_id}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='tt-regulation'>Regulasi</Label>
                    <select
                        id='tt-regulation'
                        value={data.regulation_id}
                        onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
                            setData('regulation_id', e.target.value)
                            setData('regulation_appendix_id', '')
                        }}
                        className='w-full rounded-md border bg-background px-3 py-2 text-sm'
                    >
                        <option value=''>Tanpa 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='tt-appendix'>Lampiran Regulasi</Label>
                    <select
                        id='tt-appendix'
                        value={data.regulation_appendix_id}
                        onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setData('regulation_appendix_id', e.target.value)}
                        className='w-full rounded-md border bg-background px-3 py-2 text-sm'
                    >
                        <option value=''>Tanpa lampiran</option>
                        {filteredAppendixOptions.map((option) => (
                            <option key={option.id} value={option.id}>
                                {option.appendix_number ? `${option.appendix_number} - ${option.name}` : `${option.code} - ${option.name}`}
                            </option>
                        ))}
                    </select>
                    {errors.regulation_appendix_id && <p className='text-xs text-destructive'>{errors.regulation_appendix_id}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='tt-effective-date'>Tanggal Berlaku</Label>
                    <Input
                        id='tt-effective-date'
                        type='date'
                        value={data.effective_date}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('effective_date', e.target.value)}
                    />
                    {errors.effective_date && <p className='text-xs text-destructive'>{errors.effective_date}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='tt-code'>
                        Kode
                    </Label>
                    <Input
                        id='tt-code'
                        value={data.code}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setData('code', e.target.value.toUpperCase())}
                        placeholder='e.g. TT_AIR_LIMBAH_STD'
                    />
                    <p className='text-xs text-muted-foreground'>Opsional. Jika dikosongkan, kode akan dibuat otomatis oleh sistem.</p>
                    {errors.code && <p className='text-xs text-destructive'>{errors.code}</p>}
                </div>

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

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

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