import { useState } from 'react'
import { format, parseISO } from 'date-fns'
import { id as localeId } from 'date-fns/locale'
import { CalendarIcon } from 'lucide-react'
import { useForm } from '@inertiajs/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 { Textarea } from '@ui/components/ui/textarea'
import { Checkbox } from '@ui/components/ui/checkbox'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'
import { Popover, PopoverContent, PopoverTrigger } from '@ui/components/ui/popover'
import { Calendar } from '@ui/components/ui/calendar'
import { cn } from '@ui/lib/utils'
import { type Regulation } from '@/types/glims'
import RegulationController from '@/actions/App/Modules/MasterData/Infrastructure/Controllers/RegulationController'

const REGULATION_STATUSES = [
    { value: 'BERLAKU', label: 'Berlaku' },
    { value: 'DICABUT', label: 'Dicabut' },
    { value: 'DRAFT', label: 'Draft' },
]

const REGULATION_TYPES = [
    { value: 'PP', label: 'PP' },
    { value: 'PERMEN', label: 'PerMen' },
    { value: 'PERDA', label: 'PerDa' },
    { value: 'SNI', label: 'SNI' },
    { value: 'KEPUTUSAN', label: 'Keputusan' },
]

interface RegulationFormProps {
    regulation?: Regulation
    replaceOptions: Array<{
        id: number
        code: string
        name: string
        short_name: string | null
    }>
    onSuccess: () => void
    onCancel: () => void
}

function toCodeSeed(value: string): string {
    const compact = value
        .toUpperCase()
        .replace(/[^A-Z0-9]+/g, '_')
        .replace(/^_+|_+$/g, '')
        .slice(0, 36)

    return compact || 'REGULASI'
}

function DatePickerField({
    label,
    value,
    placeholder,
    onChange,
    error,
}: {
    label: string
    value: string
    placeholder: string
    onChange: (value: string) => void
    error?: string
}) {
    const [open, setOpen] = useState(false)

    return (
        <div className='space-y-1.5'>
            <Label>{label}</Label>
            <Popover open={open} onOpenChange={setOpen}>
                <PopoverTrigger asChild>
                    <Button
                        variant='outline'
                        className={cn(
                            'w-full justify-start text-left font-normal',
                            !value && 'text-muted-foreground',
                        )}
                    >
                        <CalendarIcon className='mr-2 h-4 w-4' />
                        {value
                            ? format(parseISO(value), 'd MMMM yyyy', { locale: localeId })
                            : placeholder}
                    </Button>
                </PopoverTrigger>
                <PopoverContent className='w-auto p-0' align='start'>
                    <Calendar
                        mode='single'
                        captionLayout='dropdown'
                        selected={value ? parseISO(value) : undefined}
                        onSelect={(date) => {
                            onChange(date ? format(date, 'yyyy-MM-dd') : '')
                            setOpen(false)
                        }}
                        fromYear={1945}
                        toYear={new Date().getFullYear() + 20}
                        locale={localeId}
                    />
                </PopoverContent>
            </Popover>
            {error && <p className='text-xs text-destructive'>{error}</p>}
        </div>
    )
}

export function RegulationForm({ regulation, replaceOptions, onSuccess, onCancel }: RegulationFormProps) {
    const { data, setData, post, put, transform, processing, errors } = useForm({
        code: regulation?.code ?? '',
        name: regulation?.name ?? '',
        short_name: regulation?.short_name ?? '',
        regulation_type: regulation?.regulation_type ?? '',
        issued_date: regulation?.issued_date ?? '',
        effective_date: regulation?.effective_date ?? '',
        expired_date: regulation?.expired_date ?? '',
        replaces_regulation_id: String(regulation?.replaces_regulation_id ?? ''),
        parent_regulation_id: String(regulation?.parent_regulation_id ?? ''),
        status: regulation?.status ?? '',
        description: regulation?.description ?? '',
        is_active: regulation?.is_active ?? true,
    })

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

        transform((formData) => ({
            ...formData,
            code: regulation?.code || formData.code || `${toCodeSeed(formData.name)}_${Date.now()}`,
            regulation_type: formData.regulation_type || null,
            replaces_regulation_id: formData.replaces_regulation_id
                ? Number(formData.replaces_regulation_id)
                : null,
            parent_regulation_id: formData.parent_regulation_id
                ? Number(formData.parent_regulation_id)
                : null,
        }))

        if (regulation) {
            put(RegulationController.update(regulation).url, {
                onSuccess: () => { toast.success('Regulasi berhasil diperbarui.'); onSuccess() },
                onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Terjadi kesalahan.'),
            })
            return
        }

        post(RegulationController.store().url, {
            onSuccess: () => { toast.success('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='space-y-1.5'>
                    <Label htmlFor='r-status'>Status Regulasi</Label>
                    <ComboboxDropdown
                        value={data.status || undefined}
                        onValueChange={(value) => setData('status', value ?? '')}
                        placeholder='Pilih status...'
                        options={REGULATION_STATUSES.map((status) => ({ value: status.value, label: status.label }))}
                        searchPlaceholder='Cari status...'
                        emptyText='Status tidak ditemukan.'
                    />
                    {errors.status && <p className='text-xs text-destructive'>{errors.status}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='r-type'>Jenis Regulasi</Label>
                    <ComboboxDropdown
                        value={data.regulation_type || undefined}
                        onValueChange={(value) => setData('regulation_type', value ?? '')}
                        placeholder='Pilih jenis regulasi...'
                        options={REGULATION_TYPES.map((type) => ({ value: type.value, label: type.label }))}
                        searchPlaceholder='Cari jenis regulasi...'
                        emptyText='Jenis regulasi tidak ditemukan.'
                    />
                    {errors.regulation_type && <p className='text-xs text-destructive'>{errors.regulation_type}</p>}
                </div>

                <div className='col-span-full space-y-1.5'>
                    <Label htmlFor='r-name'>
                        Nama Regulasi <span className='text-destructive'>*</span>
                    </Label>
                    <Input
                        id='r-name'
                        value={data.name}
                        onChange={(e) => {
                            setData('name', e.target.value)
                            if (!regulation && !data.code) {
                                setData('code', toCodeSeed(e.target.value))
                            }
                        }}
                        placeholder='Contoh: Peraturan Kualitas Air Limbah'
                    />
                    {errors.name && <p className='text-xs text-destructive'>{errors.name}</p>}
                </div>

                <DatePickerField
                    label='Tanggal Terbit'
                    value={data.issued_date}
                    placeholder='Pilih tanggal terbit...'
                    onChange={(v) => setData('issued_date', v)}
                    error={errors.issued_date}
                />

                <DatePickerField
                    label='Tanggal Efektif'
                    value={data.effective_date}
                    placeholder='Pilih tanggal efektif...'
                    onChange={(v) => setData('effective_date', v)}
                    error={errors.effective_date}
                />

                <DatePickerField
                    label='Tanggal Kadaluarsa'
                    value={data.expired_date}
                    placeholder='Pilih tanggal kadaluarsa...'
                    onChange={(v) => setData('expired_date', v)}
                    error={errors.expired_date}
                />

                <div className='space-y-1.5'>
                    <Label htmlFor='r-parent'>Regulasi Induk</Label>
                    <ComboboxDropdown
                        value={data.parent_regulation_id || undefined}
                        onValueChange={(value) => setData('parent_regulation_id', value ?? '')}
                        placeholder='Pilih regulasi induk...'
                        options={replaceOptions
                            .filter((option) => !regulation || option.id !== regulation.id)
                            .map((option) => ({
                                value: String(option.id),
                                label: option.short_name ? `${option.short_name} - ${option.name}` : `${option.code} - ${option.name}`,
                            }))}
                        searchPlaceholder='Cari regulasi induk...'
                        emptyText='Regulasi tidak ditemukan.'
                    />
                    {errors.parent_regulation_id && <p className='text-xs text-destructive'>{errors.parent_regulation_id}</p>}
                </div>

                <div className='space-y-1.5'>
                    <Label htmlFor='r-replaces'>Regulasi yang Digantikan</Label>
                    <ComboboxDropdown
                        value={data.replaces_regulation_id || undefined}
                        onValueChange={(value) => setData('replaces_regulation_id', value ?? '')}
                        placeholder='Pilih regulasi yang digantikan...'
                        options={replaceOptions
                            .filter((option) => !regulation || option.id !== regulation.id)
                            .map((option) => ({
                                value: String(option.id),
                                label: option.short_name ? `${option.short_name} - ${option.name}` : `${option.code} - ${option.name}`,
                            }))}
                        searchPlaceholder='Cari regulasi yang digantikan...'
                        emptyText='Regulasi tidak ditemukan.'
                    />
                    {errors.replaces_regulation_id && <p className='text-xs text-destructive'>{errors.replaces_regulation_id}</p>}
                </div>

                <div className='col-span-full space-y-1.5'>
                    <Label htmlFor='r-desc'>Deskripsi</Label>
                    <Textarea
                        id='r-desc'
                        rows={3}
                        value={data.description}
                        onChange={(e) => setData('description', e.target.value)}
                        placeholder='Deskripsi singkat 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='r-active'
                        checked={data.is_active}
                        onCheckedChange={(v) => setData('is_active', !!v)}
                    />
                    <Label htmlFor='r-active' className='cursor-pointer font-normal'>
                        Regulasi 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...' : regulation ? 'Simpan Perubahan' : 'Simpan'}
                </Button>
            </div>
        </form>
    )
}
