import { useState, useEffect } from 'react'
import { router, useForm } from '@inertiajs/react'
import { Link } from '@inertiajs/react'
import { toast } from 'sonner'
import {
    Sheet,
    SheetContent,
    SheetHeader,
    SheetTitle,
} from '@ui/components/ui/sheet'
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@ui/components/ui/alert-dialog'
import { Badge } from '@ui/components/ui/badge'
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@ui/components/ui/tabs'
import {
    FileText,
    Paperclip,
    Info,
    ExternalLink,
    Calendar,
    Hash,
    Tag,
    AlignLeft,
    Plus,
    Pencil,
    X,
    Download,
} from 'lucide-react'
import { type Regulation, type RegulationAppendix, type RegulationAttachment } from '@/types/glims'
import { cn } from '@ui/lib/utils'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'
import { FileDropzoneField } from '@/components/common/FileDropzoneField'

// STATUS config
const STATUS_MAP: Record<string, { label: string; className: string }> = {
    BERLAKU: { label: 'Berlaku',  className: 'bg-emerald-600 text-white' },
    DICABUT: { label: 'Dicabut',  className: 'bg-red-600 text-white' },
    DRAFT:   { label: 'Draft',    className: 'bg-amber-500 text-white' },
}

function fmtDate(value: string | null): string {
    if (!value) return '-'
    return new Date(value).toLocaleDateString('id-ID', {
        day: 'numeric', month: 'long', year: 'numeric',
    })
}

function formatFileSize(size: number | null): string {
    if (!size || size <= 0) return '-'
    const units = ['B', 'KB', 'MB', 'GB']
    let value = size
    let idx = 0
    while (value >= 1024 && idx < units.length - 1) { value /= 1024; idx++ }
    return `${value.toFixed(idx === 0 ? 0 : 1)} ${units[idx]}`
}

function InfoRow({
    icon: Icon, label, value, mono = false,
}: { icon: React.ElementType; label: string; value: React.ReactNode; mono?: boolean }) {
    return (
        <div className='flex items-start gap-3 rounded-lg border bg-muted/30 px-3 py-2.5'>
            <Icon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground' />
            <div className='min-w-0 flex-1'>
                <p className='text-[10px] font-medium uppercase tracking-wide text-muted-foreground'>{label}</p>
                <p className={cn('mt-0.5 text-sm font-medium text-foreground', mono && 'font-mono text-xs')}>{value ?? '-'}</p>
            </div>
        </div>
    )
}

// Inline form: Lampiran
interface AppendixFormProps {
    appendix?: RegulationAppendix
    regulationId: number
    onSuccess: () => void
    onCancel: () => void
}

function AppendixInlineForm({ appendix, regulationId, onSuccess, onCancel }: AppendixFormProps) {
    const { data, setData, post, put, processing, errors } = useForm({
        regulation_id: regulationId,
        name: appendix?.name ?? '',
        sort_order: appendix?.sort_order ?? 0,
        description: appendix?.description ?? '',
        is_active: appendix?.is_active ?? true,
    })

    function submit(e: React.FormEvent) {
        e.preventDefault()
        const opts = {
            onSuccess: () => { toast.success(appendix ? 'Lampiran berhasil diperbarui.' : 'Lampiran berhasil ditambahkan.'); onSuccess() },
            onError: (err: Record<string, string>) => toast.error(Object.values(err)[0] ?? 'Terjadi kesalahan.'),
        }
        if (appendix) { put(`/master-data/regulation-appendices/${appendix.id}`, opts) }
        else { post('/master-data/regulation-appendices', opts) }
    }

    return (
        <form onSubmit={submit} className='space-y-3 rounded-lg border bg-muted/20 p-3'>
            <div className='flex items-center justify-between'>
                <p className='text-xs font-semibold text-foreground'>{appendix ? 'Edit Lampiran' : 'Tambah Lampiran Baru'}</p>
                <button type='button' onClick={onCancel} className='text-muted-foreground hover:text-foreground transition-colors'><X className='h-3.5 w-3.5' /></button>
            </div>
            <div className='grid grid-cols-2 gap-2.5'>
                <div className='col-span-full space-y-1'>
                    <Label className='text-xs'>Nama Lampiran <span className='text-destructive'>*</span></Label>
                    <Input className='h-7 text-xs' value={data.name} onChange={e => setData('name', e.target.value)} placeholder='Nama lampiran...' />
                    {errors.name && <p className='text-[10px] text-destructive'>{errors.name}</p>}
                </div>
                <div className='space-y-1'>
                    <Label className='text-xs'>Urutan</Label>
                    <Input className='h-7 text-xs' type='number' min='0' value={data.sort_order} onChange={e => setData('sort_order', Number(e.target.value))} />
                </div>
                <div className='col-span-full space-y-1'>
                    <Label className='text-xs'>Deskripsi</Label>
                    <Textarea className='text-xs' rows={2} value={data.description} onChange={e => setData('description', e.target.value)} placeholder='Deskripsi singkat...' />
                </div>
                <div className='col-span-full flex items-center gap-2'>
                    <Checkbox id='app-inline-active' checked={data.is_active} onCheckedChange={v => setData('is_active', !!v)} />
                    <Label htmlFor='app-inline-active' className='cursor-pointer text-xs font-normal'>Aktif</Label>
                </div>
            </div>
            <div className='flex justify-end gap-2 pt-1'>
                <Button type='button' size='sm' variant='outline' onClick={onCancel} disabled={processing}>Batal</Button>
                <Button type='submit' size='sm' disabled={processing}>{processing ? 'Menyimpan...' : 'Simpan'}</Button>
            </div>
        </form>
    )
}

// Inline form: Attachment
interface SampleTypeOption { id: number; code: string; name: string }

interface AttachmentFormProps {
    attachment?: RegulationAttachment
    regulationId: number
    sampleTypeOptions: SampleTypeOption[]
    onSuccess: () => void
    onCancel: () => void
}

function AttachmentInlineForm({ attachment, regulationId, sampleTypeOptions, onSuccess, onCancel }: AttachmentFormProps) {
    const { data, setData, post, put, processing, errors } = useForm({
        regulation_id: regulationId,
        sample_type_id: attachment?.sample_type_id ?? (null as number | null),
        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()
        const opts = {
            forceFormData: true,
            onSuccess: () => { toast.success(attachment ? 'Attachment berhasil diperbarui.' : 'Attachment berhasil ditambahkan.'); onSuccess() },
            onError: (err: Record<string, string>) => toast.error(Object.values(err)[0] ?? 'Terjadi kesalahan.'),
        }
        if (attachment) { put(`/master-data/regulation-attachments/${attachment.id}`, opts) }
        else { post('/master-data/regulation-attachments', opts) }
    }

    return (
        <form onSubmit={submit} className='space-y-3 rounded-lg border bg-muted/20 p-3'>
            <div className='flex items-center justify-between'>
                <p className='text-xs font-semibold text-foreground'>{attachment ? 'Edit Attachment' : 'Tambah Attachment Baru'}</p>
                <button type='button' onClick={onCancel} className='text-muted-foreground hover:text-foreground transition-colors'><X className='h-3.5 w-3.5' /></button>
            </div>
            <div className='grid grid-cols-2 gap-2.5'>
                <div className='col-span-full space-y-1'>
                    <Label className='text-xs'>Nama Dokumen <span className='text-destructive'>*</span></Label>
                    <Input className='h-7 text-xs' value={data.name} onChange={e => setData('name', e.target.value)} placeholder='Nama dokumen...' />
                    {errors.name && <p className='text-[10px] text-destructive'>{errors.name}</p>}
                </div>
                <div className='space-y-1'>
                    <Label className='text-xs'>Kelas Dokumen</Label>
                    <Input className='h-7 text-xs' value={data.class_name} onChange={e => setData('class_name', e.target.value)} placeholder='Lampiran I...' />
                </div>
                <div className='space-y-1'>
                    <Label className='text-xs'>Kategori</Label>
                    <Input className='h-7 text-xs' value={data.category} onChange={e => setData('category', e.target.value)} placeholder='Baku Mutu...' />
                </div>
                {sampleTypeOptions.length > 0 && (
                    <div className='col-span-full space-y-1'>
                        <Label className='text-xs'>Jenis Sampel</Label>
                        <ComboboxDropdown
                            value={data.sample_type_id ? String(data.sample_type_id) : undefined}
                            onValueChange={(value) => setData('sample_type_id', value ? Number(value) : null)}
                            placeholder='Semua Jenis Sampel'
                            options={sampleTypeOptions.map((o) => ({ value: String(o.id), label: `${o.code} - ${o.name}` }))}
                            searchPlaceholder='Cari jenis sampel...'
                            emptyText='Jenis sampel tidak ditemukan.'
                            className='h-7 text-xs'
                        />
                    </div>
                )}
                <div className='col-span-full space-y-1'>
                    <FileDropzoneField
                        id='att-inline-file'
                        label={attachment ? 'File (opsional untuk ganti)' : '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'>
                    <Label className='text-xs'>Deskripsi</Label>
                    <Textarea className='text-xs' rows={2} value={data.description} onChange={e => setData('description', e.target.value)} placeholder='Deskripsi singkat...' />
                </div>
                <div className='col-span-full flex items-center gap-2'>
                    <Checkbox id='att-inline-active' checked={data.is_active} onCheckedChange={v => setData('is_active', !!v)} />
                    <Label htmlFor='att-inline-active' className='cursor-pointer text-xs font-normal'>Aktif</Label>
                </div>
            </div>
            <div className='flex justify-end gap-2 pt-1'>
                <Button type='button' size='sm' variant='outline' onClick={onCancel} disabled={processing}>Batal</Button>
                <Button type='submit' size='sm' disabled={processing}>{processing ? 'Menyimpan...' : 'Simpan'}</Button>
            </div>
        </form>
    )
}

// Props
interface RegulationDetailDrawerProps {
    regulation: Regulation | undefined
    open: boolean
    onOpenChange: (open: boolean) => void
    defaultTab?: 'info' | 'lampiran' | 'attachment'
    sampleTypeOptions?: SampleTypeOption[]
    onEdit?: (regulation: Regulation) => void
    onMutate?: () => void
}

// Component
export function RegulationDetailDrawer({
    regulation,
    open,
    onOpenChange,
    defaultTab = 'info',
    sampleTypeOptions = [],
    onEdit,
    onMutate,
}: RegulationDetailDrawerProps) {
    const [activeTab, setActiveTab] = useState(defaultTab)

    // Lampiran CRUD state
    const [appendixMode, setAppendixMode] = useState<'none' | 'create' | 'edit'>('none')
    const [editingAppendix, setEditingAppendix] = useState<RegulationAppendix | undefined>()
    const [deletingAppendix, setDeletingAppendix] = useState<RegulationAppendix | undefined>()
    const [isDeletingAppendix, setIsDeletingAppendix] = useState(false)

    // Attachment CRUD state
    const [attachmentMode, setAttachmentMode] = useState<'none' | 'create' | 'edit'>('none')
    const [editingAttachment, setEditingAttachment] = useState<RegulationAttachment | undefined>()
    const [deletingAttachment, setDeletingAttachment] = useState<RegulationAttachment | undefined>()
    const [isDeletingAttachment, setIsDeletingAttachment] = useState(false)

    useEffect(() => {
        if (open) {
            setActiveTab(defaultTab)
            setAppendixMode('none')
            setAttachmentMode('none')
        }
    }, [open, defaultTab])

    const handleOpenChange = (next: boolean) => {
        if (!next) {
            setActiveTab('info')
            setAppendixMode('none')
            setAttachmentMode('none')
        }
        onOpenChange(next)
    }

    function handleMutate() {
        router.reload({ only: ['regulations'] })
        onMutate?.()
    }

    function handleDeleteAppendix() {
        if (!deletingAppendix) return
        const name = deletingAppendix.name
        router.delete(`/master-data/regulation-appendices/${deletingAppendix.id}`, {
            onStart: () => setIsDeletingAppendix(true),
            onSuccess: () => { toast.success(`Lampiran "${name}" berhasil dihapus.`); setDeletingAppendix(undefined); handleMutate() },
            onError: () => toast.error('Gagal menghapus lampiran.'),
            onFinish: () => setIsDeletingAppendix(false),
        })
    }

    function handleDeleteAttachment() {
        if (!deletingAttachment) return
        const name = deletingAttachment.name
        router.delete(`/master-data/regulation-attachments/${deletingAttachment.id}`, {
            onStart: () => setIsDeletingAttachment(true),
            onSuccess: () => { toast.success(`Attachment "${name}" berhasil dihapus.`); setDeletingAttachment(undefined); handleMutate() },
            onError: () => toast.error('Gagal menghapus attachment.'),
            onFinish: () => setIsDeletingAttachment(false),
        })
    }

    if (!regulation) return null

    const statusMeta     = regulation.status ? (STATUS_MAP[regulation.status] ?? null) : null
    const appendixHref   = `/master-data/regulation-appendices?regulation_id=${regulation.id}`
    const attachmentHref = `/master-data/regulation-attachments?regulation_id=${regulation.id}`
    const appendices     = regulation.appendices ?? []
    const attachments    = regulation.attachments ?? []

    return (
        <>
            <Sheet open={open} onOpenChange={handleOpenChange}>
                <SheetContent side='right' className='flex w-full flex-col gap-0 overflow-hidden p-0 sm:max-w-[520px]'>

                    {/* Header */}
                    <SheetHeader className='shrink-0 border-b px-5 py-4'>
                        <div className='flex items-start justify-between gap-3 pr-8'>
                            <div className='min-w-0 flex-1'>
                                <p className='mb-1 text-[10px] font-semibold tracking-widest text-muted-foreground'>{regulation.code}</p>
                                <SheetTitle className='line-clamp-2 text-base font-bold leading-snug text-foreground'>{regulation.name}</SheetTitle>
                            </div>
                            <div className='flex shrink-0 flex-col items-end gap-1.5 text-right'>
                                {statusMeta && <Badge className={cn('text-[10px] font-medium', statusMeta.className)}>{statusMeta.label}</Badge>}
                                <div className='flex gap-1.5'>
                                    <button onClick={() => setActiveTab('lampiran')} className='inline-flex items-center gap-1 rounded-md border bg-muted/40 px-2 py-1 text-[10px] text-muted-foreground transition-colors hover:bg-muted' title='Lihat lampiran'>
                                        <FileText className='h-3 w-3' />{regulation.appendices_count ?? appendices.length}
                                    </button>
                                    <button onClick={() => setActiveTab('attachment')} className='inline-flex items-center gap-1 rounded-md border bg-muted/40 px-2 py-1 text-[10px] text-muted-foreground transition-colors hover:bg-muted' title='Lihat attachment'>
                                        <Paperclip className='h-3 w-3' />{regulation.attachments_count ?? attachments.length}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </SheetHeader>

                    {/* Tabs */}
                    <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as typeof activeTab)} className='flex min-h-0 flex-1 flex-col'>
                        <TabsList className='h-auto w-full shrink-0 rounded-none border-b bg-background px-4 py-2'>
                            <TabsTrigger value='info' className='flex-1 text-xs data-[state=active]:bg-muted data-[state=active]:text-foreground'>
                                <Info className='mr-1.5 h-3.5 w-3.5' /> Info
                            </TabsTrigger>
                            <TabsTrigger value='lampiran' className='flex-1 text-xs data-[state=active]:bg-muted data-[state=active]:text-foreground'>
                                <FileText className='mr-1.5 h-3.5 w-3.5' /> Lampiran
                                <Badge variant='secondary' className='ml-1.5 h-4 px-1.5 text-[10px]'>{regulation.appendices_count ?? appendices.length}</Badge>
                            </TabsTrigger>
                            <TabsTrigger value='attachment' className='flex-1 text-xs data-[state=active]:bg-muted data-[state=active]:text-foreground'>
                                <Paperclip className='mr-1.5 h-3.5 w-3.5' /> Attachment
                                <Badge variant='secondary' className='ml-1.5 h-4 px-1.5 text-[10px]'>{regulation.attachments_count ?? attachments.length}</Badge>
                            </TabsTrigger>
                        </TabsList>

                        {/* Tab Info */}
                        <TabsContent value='info' className='m-0 flex-1 overflow-y-auto p-4'>
                            <div className='space-y-2'>
                                <InfoRow icon={Hash}      label='Kode'            value={regulation.code} mono />
                                <InfoRow icon={Tag}       label='Jenis Regulasi'  value={regulation.regulation_type ?? '-'} />
                                <InfoRow icon={Calendar}  label='Tanggal Terbit'  value={fmtDate(regulation.issued_date)} />
                                <InfoRow icon={Calendar}  label='Tanggal Efektif' value={fmtDate(regulation.effective_date)} />
                                {regulation.expired_date && (
                                    <InfoRow icon={Calendar} label='Tanggal Expired' value={fmtDate(regulation.expired_date)} />
                                )}
                                <InfoRow icon={Tag} label='Status Regulasi' value={statusMeta ? <Badge className={cn('text-xs', statusMeta.className)}>{statusMeta.label}</Badge> : '-'} />
                                <InfoRow icon={Tag} label='Status Aktif' value={regulation.is_active ? <Badge className='bg-emerald-600 text-xs text-white'>Aktif</Badge> : <Badge variant='secondary' className='text-xs'>Nonaktif</Badge>} />
                                {regulation.description && (
                                    <InfoRow icon={AlignLeft} label='Deskripsi' value={<span className='whitespace-pre-wrap leading-relaxed'>{regulation.description}</span>} />
                                )}
                            </div>
                        </TabsContent>

                        {/* Tab Lampiran */}
                        <TabsContent value='lampiran' className='m-0 flex-1 overflow-y-auto'>
                            <div className='flex flex-col gap-3 p-4'>
                                <div className='flex items-center justify-between'>
                                    <p className='text-xs font-semibold uppercase tracking-wide text-muted-foreground'>Daftar Lampiran</p>
                                    <div className='flex items-center gap-2'>
                                        <Button size='sm' variant='outline' className='h-7 gap-1.5 text-xs' onClick={() => { setEditingAppendix(undefined); setAppendixMode('create') }}>
                                            <Plus className='h-3 w-3' /> Tambah
                                        </Button>
                                        <Button asChild size='sm' variant='ghost' className='h-7 gap-1 text-xs'>
                                            <Link href={appendixHref}><ExternalLink className='h-3 w-3' /> Full</Link>
                                        </Button>
                                    </div>
                                </div>

                                {appendixMode !== 'none' && (
                                    <AppendixInlineForm
                                        appendix={appendixMode === 'edit' ? editingAppendix : undefined}
                                        regulationId={regulation.id}
                                        onSuccess={() => { setAppendixMode('none'); handleMutate() }}
                                        onCancel={() => setAppendixMode('none')}
                                    />
                                )}

                                {appendices.length === 0 ? (
                                    <div className='rounded-lg border border-dashed bg-muted/20 p-6 text-center'>
                                        <FileText className='mx-auto mb-2 h-8 w-8 text-muted-foreground/40' />
                                        <p className='text-xs text-muted-foreground'>Belum ada lampiran.</p>
                                    </div>
                                ) : (
                                    <div className='space-y-1.5'>
                                        {appendices.map(item => (
                                            <div key={item.id} className='flex items-start gap-2 rounded-lg border bg-card px-3 py-2 transition-colors hover:bg-muted/30'>
                                                <div className='min-w-0 flex-1'>
                                                    <div className='flex items-center gap-2'>
                                                        <span className='font-mono text-[10px] text-muted-foreground'>{item.code}</span>
                                                        {!item.is_active && <Badge variant='secondary' className='h-3.5 px-1 text-[9px]'>Nonaktif</Badge>}
                                                    </div>
                                                    <p className='mt-0.5 line-clamp-2 text-xs font-medium leading-snug text-foreground'>{item.name}</p>
                                                </div>
                                                <div className='flex shrink-0 gap-0.5'>
                                                    <Button size='icon' variant='ghost' className='h-6 w-6' title='Edit' onClick={() => { setEditingAppendix(item); setAppendixMode('edit') }}>
                                                        <Pencil className='h-3 w-3' />
                                                    </Button>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        </TabsContent>

                        {/* Tab Attachment */}
                        <TabsContent value='attachment' className='m-0 flex-1 overflow-y-auto'>
                            <div className='flex flex-col gap-3 p-4'>
                                <div className='flex items-center justify-between'>
                                    <p className='text-xs font-semibold uppercase tracking-wide text-muted-foreground'>Daftar Attachment</p>
                                    <div className='flex items-center gap-2'>
                                        <Button size='sm' variant='outline' className='h-7 gap-1.5 text-xs' onClick={() => { setEditingAttachment(undefined); setAttachmentMode('create') }}>
                                            <Plus className='h-3 w-3' /> Tambah
                                        </Button>
                                        <Button asChild size='sm' variant='ghost' className='h-7 gap-1 text-xs'>
                                            <Link href={attachmentHref}><ExternalLink className='h-3 w-3' /> Full</Link>
                                        </Button>
                                    </div>
                                </div>

                                {attachmentMode !== 'none' && (
                                    <AttachmentInlineForm
                                        attachment={attachmentMode === 'edit' ? editingAttachment : undefined}
                                        regulationId={regulation.id}
                                        sampleTypeOptions={sampleTypeOptions}
                                        onSuccess={() => { setAttachmentMode('none'); handleMutate() }}
                                        onCancel={() => setAttachmentMode('none')}
                                    />
                                )}

                                {attachments.length === 0 ? (
                                    <div className='rounded-lg border border-dashed bg-muted/20 p-6 text-center'>
                                        <Paperclip className='mx-auto mb-2 h-8 w-8 text-muted-foreground/40' />
                                        <p className='text-xs text-muted-foreground'>Belum ada file attachment.</p>
                                    </div>
                                ) : (
                                    <div className='space-y-1.5'>
                                        {attachments.map(item => (
                                            <div key={item.id} className='flex items-start gap-2 rounded-lg border bg-card px-3 py-2 transition-colors hover:bg-muted/30'>
                                                <div className='min-w-0 flex-1'>
                                                    <div className='flex flex-wrap items-center gap-1.5'>
                                                        {item.class_name && <span className='text-[10px] text-muted-foreground'>{item.class_name}</span>}
                                                        {item.category && <Badge variant='outline' className='h-3.5 px-1 text-[9px]'>{item.category}</Badge>}
                                                        {!item.is_active && <Badge variant='secondary' className='h-3.5 px-1 text-[9px]'>Nonaktif</Badge>}
                                                    </div>
                                                    <p className='mt-0.5 line-clamp-1 text-xs font-medium text-foreground'>{item.name}</p>
                                                    {item.file_name && (
                                                        <p className='mt-0.5 text-[10px] text-muted-foreground'>{item.file_name}{item.file_size ? ` - ${formatFileSize(item.file_size)}` : ''}</p>
                                                    )}
                                                </div>
                                                <div className='flex shrink-0 gap-0.5'>
                                                    <Button size='icon' variant='ghost' className='h-6 w-6 text-muted-foreground' title='Download' onClick={() => { window.location.href = `/master-data/regulation-attachments/${item.id}/download` }}>
                                                        <Download className='h-3 w-3' />
                                                    </Button>
                                                    <Button size='icon' variant='ghost' className='h-6 w-6' title='Edit' onClick={() => { setEditingAttachment(item); setAttachmentMode('edit') }}>
                                                        <Pencil className='h-3 w-3' />
                                                    </Button>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        </TabsContent>
                    </Tabs>

                    {/* Footer */}
                    <div className='shrink-0 border-t bg-background p-3'>
                        <div className='flex justify-end gap-2'>
                            {onEdit && (
                                <Button size='sm' className='gap-1.5' onClick={() => { onEdit(regulation); onOpenChange(false) }}>
                                    Edit Regulasi
                                </Button>
                            )}
                            <Button size='sm' variant='outline' onClick={() => onOpenChange(false)}>Tutup</Button>
                        </div>
                    </div>
                </SheetContent>
            </Sheet>

            {/* Delete Lampiran Dialog */}
            <AlertDialog open={!!deletingAppendix} onOpenChange={o => !o && setDeletingAppendix(undefined)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Hapus Lampiran?</AlertDialogTitle>
                        <AlertDialogDescription>
                            Lampiran <strong>{deletingAppendix?.name}</strong> akan dihapus permanen. Tindakan ini tidak dapat dibatalkan.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={isDeletingAppendix}>Batal</AlertDialogCancel>
                        <AlertDialogAction onClick={handleDeleteAppendix} disabled={isDeletingAppendix} className='bg-destructive text-destructive-foreground hover:bg-destructive/90'>
                            {isDeletingAppendix ? 'Menghapus...' : 'Hapus'}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Delete Attachment Dialog */}
            <AlertDialog open={!!deletingAttachment} onOpenChange={o => !o && setDeletingAttachment(undefined)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Hapus Attachment?</AlertDialogTitle>
                        <AlertDialogDescription>
                            Attachment <strong>{deletingAttachment?.name}</strong> beserta filenya akan dihapus permanen. Tindakan ini tidak dapat dibatalkan.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={isDeletingAttachment}>Batal</AlertDialogCancel>
                        <AlertDialogAction onClick={handleDeleteAttachment} disabled={isDeletingAttachment} className='bg-destructive text-destructive-foreground hover:bg-destructive/90'>
                            {isDeletingAttachment ? 'Menghapus...' : 'Hapus'}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    )
}
