import { Head, router, useForm } from '@inertiajs/react'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'
import { ServerDataTable } from '@ui/components/data-table/server-data-table'
import type { ServerColumnDef, ServerDataTableParams, ServerPaginatedData } from '@ui/components/data-table/server-data-table'
import { Badge } from '@ui/components/ui/badge'
import { Button } from '@ui/components/ui/button'
import { Label } from '@ui/components/ui/label'
import { Textarea } from '@ui/components/ui/textarea'
import { Check, Eye, Plus, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { ResizableDrawer } from '@/components/common/ResizableDrawer'
import { LimsAppLayout } from '@/layouts/lims-app-layout'
import type { QualityStandardApprovalRequest } from '@/types/glims'

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

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

interface AppendixOption {
    id: number
    regulation_id: number
    appendix_number: string | null
    name: string
}

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

interface Props {
    approvalRequests: ServerPaginatedData<QualityStandardApprovalRequest>
    filters: Record<string, string | undefined>
    sampleTypeOptions: SampleTypeOption[]
    regulationOptions: RegulationOption[]
    appendixOptions: AppendixOption[]
    parameterOptions: ParameterOption[]
}

const STATUS_LABELS: Record<string, string> = {
    pending: 'Pending',
    approved: 'Approved',
    rejected: 'Rejected',
}

const STATUS_FILTER_OPTIONS = [
    { value: 'pending', label: STATUS_LABELS.pending },
    { value: 'approved', label: STATUS_LABELS.approved },
    { value: 'rejected', label: STATUS_LABELS.rejected },
]

function statusBadgeVariant(status: string): 'secondary' | 'default' | 'destructive' {
    if (status === 'approved') {
        return 'default'
    }

    if (status === 'rejected') {
        return 'destructive'
    }

    return 'secondary'
}

function sourceBadge(source: 'existing' | 'new') {
    if (source === 'new') {
        return <Badge className='border-amber-200 bg-amber-50 text-amber-700'>Baru</Badge>
    }

    return <Badge variant='outline'>Sudah Ada</Badge>
}

function formatDateTime(value?: string | null): string {
    if (!value) {
        return '-'
    }

    return new Date(value).toLocaleString('id-ID', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    })
}

function matrixDisplay(row: QualityStandardApprovalRequest, type: 'sample' | 'regulation' | 'appendix' | 'parameter'): string {
    if (type === 'sample') {
        if (row.sample_type) {
            return `${row.sample_type.code} - ${row.sample_type.name}`
        }

        return row.requested_sample_type_name || '-'
    }

    if (type === 'regulation') {
        if (row.regulation) {
            return `${row.regulation.short_name ?? row.regulation.code} - ${row.regulation.name}`
        }

        return row.requested_regulation_name || '-'
    }

    if (type === 'appendix') {
        if (row.regulation_appendix) {
            return `${row.regulation_appendix.appendix_number ?? '-'} - ${row.regulation_appendix.name}`
        }

        return row.requested_regulation_appendix_name || '-'
    }

    if (row.requested_parameter) {
        return `${row.requested_parameter.code} - ${row.requested_parameter.name}`
    }

    return row.requested_parameter_name || '-'
}

export default function QualityStandardApprovalIndex({
    approvalRequests,
    filters,
    sampleTypeOptions,
    regulationOptions,
    appendixOptions,
    parameterOptions,
}: Props) {
    const [isRequestDrawerOpen, setIsRequestDrawerOpen] = useState(false)
    const [isDetailDrawerOpen, setIsDetailDrawerOpen] = useState(false)
    const [isRejectDrawerOpen, setIsRejectDrawerOpen] = useState(false)
    const [selectedDetailItem, setSelectedDetailItem] = useState<QualityStandardApprovalRequest | undefined>()
    const [selectedRejectItem, setSelectedRejectItem] = useState<QualityStandardApprovalRequest | undefined>()
    const [rejectNote, setRejectNote] = useState('')

    const requestForm = useForm({
        sample_type_id: '',
        sample_type_name: '',
        regulation_id: '',
        regulation_name: '',
        regulation_appendix_id: '',
        regulation_appendix_name: '',
        requested_parameter_id: '',
        requested_parameter_name: '',
        description: '',
        request_note: '',
    })

    const params: ServerDataTableParams = {
        page: approvalRequests.current_page,
        per_page: approvalRequests.per_page,
        search: filters.search,
    }

    const filteredAppendixOptions = useMemo(() => {
        if (!requestForm.data.regulation_id) {
            return []
        }

        const regulationId = Number(requestForm.data.regulation_id)

        return appendixOptions.filter((item) => item.regulation_id === regulationId)
    }, [appendixOptions, requestForm.data.regulation_id])

    const columns: ServerColumnDef<QualityStandardApprovalRequest>[] = [
        {
            key: 'request_number',
            label: 'No Request',
            sortable: true,
            render: (row) => (
                <button
                    type='button'
                    className='font-medium text-left hover:underline'
                    onClick={() => openDetail(row)}
                >
                    {row.request_number}
                </button>
            ),
        },
        {
            key: 'requested_at',
            label: 'Tgl Request',
            sortable: true,
            render: (row) => new Date(row.requested_at).toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }),
        },
        {
            key: 'sample_type_source',
            label: 'Jenis Sampel',
            render: (row) => (
                <div className='space-y-1'>
                    {sourceBadge(row.sample_type_source)}
                    <p className='max-w-[200px] truncate text-xs text-muted-foreground'>{matrixDisplay(row, 'sample')}</p>
                </div>
            ),
        },
        {
            key: 'regulation_source',
            label: 'Regulasi',
            render: (row) => (
                <div className='space-y-1'>
                    {sourceBadge(row.regulation_source)}
                    <p className='max-w-[220px] truncate text-xs text-muted-foreground'>{matrixDisplay(row, 'regulation')}</p>
                </div>
            ),
        },
        {
            key: 'regulation_appendix_source',
            label: 'Lampiran',
            render: (row) => (
                <div className='space-y-1'>
                    {sourceBadge(row.regulation_appendix_source)}
                    <p className='max-w-[220px] truncate text-xs text-muted-foreground'>{matrixDisplay(row, 'appendix')}</p>
                </div>
            ),
        },
        {
            key: 'parameter_source',
            label: 'Parameter',
            render: (row) => (
                <div className='space-y-1'>
                    {sourceBadge(row.parameter_source)}
                    <p className='max-w-[220px] truncate text-xs text-muted-foreground'>{matrixDisplay(row, 'parameter')}</p>
                </div>
            ),
        },
        {
            key: 'status',
            label: 'Status',
            render: (row) => <Badge variant={statusBadgeVariant(row.status)}>{STATUS_LABELS[row.status] ?? row.status}</Badge>,
        },
        {
            key: 'actions',
            label: '',
            className: 'w-52 text-right',
            render: (row) => (
                <div className='flex justify-end gap-1'>
                    <Button
                        size='sm'
                        variant='ghost'
                        className='h-7 gap-1 px-2'
                        onClick={() => openDetail(row)}
                    >
                        <Eye className='h-3.5 w-3.5' />
                        Lihat
                    </Button>
                    {row.status === 'pending' ? (
                        <>
                            <Button
                                size='sm'
                                className='h-7 gap-1 px-2'
                                onClick={() => {
                                    router.patch(`/master-data/quality-standard-approvals/${row.id}/approve`, {}, {
                                        preserveScroll: true,
                                        onSuccess: () => toast.success('Permintaan berhasil disetujui.'),
                                        onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Gagal menyetujui permintaan.'),
                                    })
                                }}
                            >
                                <Check className='h-3.5 w-3.5' />
                                Approve
                            </Button>
                            <Button
                                size='sm'
                                variant='outline'
                                className='h-7 gap-1 px-2 text-destructive hover:text-destructive'
                                onClick={() => {
                                    setSelectedRejectItem(row)
                                    setRejectNote('')
                                    setIsRejectDrawerOpen(true)
                                }}
                            >
                                <X className='h-3.5 w-3.5' />
                                Reject
                            </Button>
                        </>
                    ) : (
                        <span className='text-xs text-muted-foreground'>Sudah diproses</span>
                    )}
                </div>
            ),
        },
    ]

    useEffect(() => {
        if (typeof window === 'undefined' || typeof EventSource === 'undefined') {
            return
        }

        const eventSource = new EventSource('/master-data/quality-standard-approvals/stream')

        const handleRealtimeEvent = (event: MessageEvent) => {
            try {
                const payload = JSON.parse(event.data) as {
                    event?: string
                    request_number?: string
                }

                const requestNumber = payload.request_number ?? '-'
                const actionLabel =
                    payload.event === 'submitted'
                        ? 'diajukan'
                        : payload.event === 'approved'
                            ? 'disetujui'
                            : payload.event === 'rejected'
                                ? 'ditolak'
                                : 'diperbarui'

                toast.info(`Request ${requestNumber} ${actionLabel}.`)
                router.reload({
                    only: ['approvalRequests'],
                    preserveState: true,
                    preserveScroll: true,
                })
            } catch {
                // ignore malformed payload
            }
        }

        eventSource.addEventListener('quality-standard-approval', handleRealtimeEvent)

        return () => {
            eventSource.removeEventListener('quality-standard-approval', handleRealtimeEvent)
            eventSource.close()
        }
    }, [])

    function handleParamsChange(next: ServerDataTableParams) {
        router.get('/master-data/quality-standard-approvals', { ...filters, ...next } as Record<string, string | number | undefined>, {
            preserveState: true,
            replace: true,
        })
    }

    function openDetail(item: QualityStandardApprovalRequest) {
        setSelectedDetailItem(item)
        setIsDetailDrawerOpen(true)
    }

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

        requestForm.transform((data) => ({
            sample_type_id: data.sample_type_id ? Number(data.sample_type_id) : null,
            sample_type_name: data.sample_type_name || null,
            regulation_id: data.regulation_id ? Number(data.regulation_id) : null,
            regulation_name: data.regulation_name || null,
            regulation_appendix_id: data.regulation_appendix_id ? Number(data.regulation_appendix_id) : null,
            regulation_appendix_name: data.regulation_appendix_name || null,
            requested_parameter_id: data.requested_parameter_id ? Number(data.requested_parameter_id) : null,
            requested_parameter_name: data.requested_parameter_name || null,
            description: data.description || null,
            request_note: data.request_note || null,
        }))

        requestForm.post('/master-data/quality-standard-approvals', {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Permintaan sustain berhasil diajukan.')
                requestForm.reset()
                setIsRequestDrawerOpen(false)
            },
            onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Gagal mengajukan permintaan.'),
        })
    }

    function submitReject() {
        if (!selectedRejectItem) {
            return
        }

        router.patch(`/master-data/quality-standard-approvals/${selectedRejectItem.id}/reject`, {
            review_note: rejectNote,
        }, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Permintaan berhasil ditolak.')
                setIsRejectDrawerOpen(false)
                setSelectedRejectItem(undefined)
                setRejectNote('')
            },
            onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Gagal menolak permintaan.'),
        })
    }

    return (
        <LimsAppLayout>
            <Head title='Approval Baku Mutu' />

            <div className='flex h-full flex-1 flex-col gap-4 p-4'>
                <div className='flex items-center justify-between'>
                    <div>
                        <h1 className='text-xl font-bold tracking-tight'>Approval Baku Mutu</h1>
                        <p className='text-sm text-muted-foreground'>
                            Menu sustain untuk melengkapi 4 matriks (jenis sampel, regulasi, lampiran, parameter) dan plotting saat approve.
                        </p>
                    </div>
                    <Button className='gap-2' onClick={() => setIsRequestDrawerOpen(true)}>
                        <Plus className='h-4 w-4' />
                        Ajukan Sustain
                    </Button>
                </div>

                <div className='flex flex-wrap gap-2'>
                    {(['', '1', '0'] as const).map((active) => (
                        <button
                            key={active || 'all-active'}
                            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
                                (filters.is_active ?? '') === active
                                    ? 'bg-teal-600 text-white'
                                    : 'bg-muted text-muted-foreground hover:bg-muted/80'
                            }`}
                            onClick={() => {
                                router.get('/master-data/quality-standard-approvals', {
                                    ...filters,
                                    is_active: active || undefined,
                                }, {
                                    preserveState: true,
                                    replace: true,
                                })
                            }}
                        >
                            {active === '' ? 'Semua' : active === '1' ? 'Aktif' : 'Nonaktif'}
                        </button>
                    ))}
                </div>

                <div className='w-full sm:w-[240px]'>
                    <ComboboxDropdown
                        value={filters.status || undefined}
                        onValueChange={(value) => {
                            router.get('/master-data/quality-standard-approvals', {
                                ...filters,
                                status: value || undefined,
                            }, {
                                preserveState: true,
                                replace: true,
                            })
                        }}
                        placeholder='Semua Status'
                        options={STATUS_FILTER_OPTIONS}
                        searchPlaceholder='Cari status...'
                        emptyText='Status tidak ditemukan.'
                    />
                </div>

                <ServerDataTable
                    data={approvalRequests}
                    columns={columns}
                    params={params}
                    onParamsChange={handleParamsChange}
                    searchPlaceholder='Cari no request atau nama matriks...'
                    emptyText='Belum ada permintaan sustain.'
                />
            </div>

            <ResizableDrawer
                open={isDetailDrawerOpen}
                onOpenChange={setIsDetailDrawerOpen}
                title={selectedDetailItem ? `Detail ${selectedDetailItem.request_number}` : 'Detail Request'}
                description='Ringkasan sustain 4 matriks untuk proses approve.'
            >
                {selectedDetailItem ? (
                    <div className='space-y-4'>
                        <div className='rounded-lg border p-3'>
                            <p className='text-xs text-muted-foreground'>Status</p>
                            <div className='mt-1'>
                                <Badge variant={statusBadgeVariant(selectedDetailItem.status)}>
                                    {STATUS_LABELS[selectedDetailItem.status] ?? selectedDetailItem.status}
                                </Badge>
                            </div>
                        </div>

                        <div className='space-y-2 rounded-lg border p-3 text-sm'>
                            <p className='text-xs font-semibold uppercase tracking-wide text-muted-foreground'>4 Matriks Sustain</p>

                            <div className='space-y-1'>
                                <p><span className='text-muted-foreground'>Jenis Sampel:</span> {matrixDisplay(selectedDetailItem, 'sample')}</p>
                                {sourceBadge(selectedDetailItem.sample_type_source)}
                            </div>

                            <div className='space-y-1'>
                                <p><span className='text-muted-foreground'>Regulasi:</span> {matrixDisplay(selectedDetailItem, 'regulation')}</p>
                                {sourceBadge(selectedDetailItem.regulation_source)}
                            </div>

                            <div className='space-y-1'>
                                <p><span className='text-muted-foreground'>Lampiran:</span> {matrixDisplay(selectedDetailItem, 'appendix')}</p>
                                {sourceBadge(selectedDetailItem.regulation_appendix_source)}
                            </div>

                            <div className='space-y-1'>
                                <p><span className='text-muted-foreground'>Parameter:</span> {matrixDisplay(selectedDetailItem, 'parameter')}</p>
                                {sourceBadge(selectedDetailItem.parameter_source)}
                            </div>
                        </div>

                        <div className='space-y-2 rounded-lg border p-3 text-sm'>
                            <p className='text-xs font-semibold uppercase tracking-wide text-muted-foreground'>Catatan & Review</p>
                            <p><span className='text-muted-foreground'>Catatan Pengajuan:</span> {selectedDetailItem.request_note || '-'}</p>
                            <p><span className='text-muted-foreground'>Deskripsi:</span> {selectedDetailItem.description || '-'}</p>
                            <p><span className='text-muted-foreground'>Diajukan:</span> {formatDateTime(selectedDetailItem.requested_at)}</p>
                            <p><span className='text-muted-foreground'>Direview:</span> {formatDateTime(selectedDetailItem.reviewed_at)}</p>
                            <p><span className='text-muted-foreground'>Catatan Review:</span> {selectedDetailItem.review_note || '-'}</p>
                        </div>

                        <div className='flex justify-end gap-2'>
                            <Button type='button' variant='outline' onClick={() => setIsDetailDrawerOpen(false)}>
                                Tutup
                            </Button>
                            {selectedDetailItem.status === 'pending' && (
                                <Button
                                    type='button'
                                    variant='destructive'
                                    onClick={() => {
                                        setIsDetailDrawerOpen(false)
                                        setSelectedRejectItem(selectedDetailItem)
                                        setRejectNote('')
                                        setIsRejectDrawerOpen(true)
                                    }}
                                >
                                    Reject Request
                                </Button>
                            )}
                        </div>
                    </div>
                ) : null}
            </ResizableDrawer>

            <ResizableDrawer
                open={isRequestDrawerOpen}
                onOpenChange={setIsRequestDrawerOpen}
                title='Ajukan Sustain Baku Mutu'
                description='Lengkapi 4 matriks inti. Data baru akan dibuat saat request disetujui.'
            >
                <form onSubmit={submitRequest} className='space-y-4'>
                    <div className='rounded-lg border bg-muted/30 p-3 text-xs text-muted-foreground'>
                        Wajib melengkapi: jenis sampel, regulasi, lampiran regulasi, dan parameter.
                    </div>

                    <div className='space-y-1.5'>
                        <Label>Jenis Sampel <span className='text-destructive'>*</span></Label>
                        <ComboboxDropdown
                            value={requestForm.data.sample_type_id || requestForm.data.sample_type_name || undefined}
                            onValueChange={(value) => {
                                const nextValue = value ?? ''
                                const selected = sampleTypeOptions.find((item) => String(item.id) === nextValue)

                                if (selected) {
                                    requestForm.setData('sample_type_id', nextValue)
                                    requestForm.setData('sample_type_name', '')

                                    return
                                }

                                requestForm.setData('sample_type_id', '')
                                requestForm.setData('sample_type_name', nextValue)
                            }}
                            options={sampleTypeOptions.map((item) => ({
                                value: String(item.id),
                                label: `${item.code} - ${item.name}`,
                            }))}
                            placeholder='Pilih jenis sampel...'
                            searchPlaceholder='Cari jenis sampel...'
                            emptyText='Jenis sampel tidak ditemukan.'
                            allowCustomOption
                            customOptionLabel='Tambah jenis sampel baru'
                        />
                        {requestForm.errors.sample_type_id && <p className='text-xs text-destructive'>{requestForm.errors.sample_type_id}</p>}
                        {requestForm.errors.sample_type_name && <p className='text-xs text-destructive'>{requestForm.errors.sample_type_name}</p>}
                    </div>

                    <div className='space-y-1.5'>
                        <Label>Regulasi <span className='text-destructive'>*</span></Label>
                        <ComboboxDropdown
                            value={requestForm.data.regulation_id || requestForm.data.regulation_name || undefined}
                            onValueChange={(value) => {
                                const nextValue = value ?? ''
                                const selected = regulationOptions.find((item) => String(item.id) === nextValue)

                                if (selected) {
                                    requestForm.setData('regulation_id', nextValue)
                                    requestForm.setData('regulation_name', '')
                                } else {
                                    requestForm.setData('regulation_id', '')
                                    requestForm.setData('regulation_name', nextValue)
                                }

                                requestForm.setData('regulation_appendix_id', '')
                                requestForm.setData('regulation_appendix_name', '')
                            }}
                            options={regulationOptions.map((item) => ({
                                value: String(item.id),
                                label: `${item.short_name ?? item.code} - ${item.name}`,
                            }))}
                            placeholder='Pilih regulasi...'
                            searchPlaceholder='Cari regulasi...'
                            emptyText='Regulasi tidak ditemukan.'
                            allowCustomOption
                            customOptionLabel='Tambah regulasi baru'
                        />
                        {requestForm.errors.regulation_id && <p className='text-xs text-destructive'>{requestForm.errors.regulation_id}</p>}
                        {requestForm.errors.regulation_name && <p className='text-xs text-destructive'>{requestForm.errors.regulation_name}</p>}
                    </div>

                    <div className='space-y-1.5'>
                        <Label>Lampiran Regulasi <span className='text-destructive'>*</span></Label>
                        <ComboboxDropdown
                            value={requestForm.data.regulation_appendix_id || requestForm.data.regulation_appendix_name || undefined}
                            onValueChange={(value) => {
                                const nextValue = value ?? ''
                                const selected = filteredAppendixOptions.find((item) => String(item.id) === nextValue)

                                if (selected) {
                                    requestForm.setData('regulation_appendix_id', nextValue)
                                    requestForm.setData('regulation_appendix_name', '')

                                    return
                                }

                                requestForm.setData('regulation_appendix_id', '')
                                requestForm.setData('regulation_appendix_name', nextValue)
                            }}
                            options={filteredAppendixOptions.map((item) => ({
                                value: String(item.id),
                                label: `${item.appendix_number ?? '-'} - ${item.name}`,
                            }))}
                            placeholder='Pilih lampiran regulasi...'
                            searchPlaceholder='Cari lampiran...'
                            emptyText={requestForm.data.regulation_id ? 'Lampiran tidak ditemukan.' : 'Pilih regulasi dahulu.'}
                            allowCustomOption
                            customOptionLabel='Tambah lampiran baru'
                        />
                        {requestForm.errors.regulation_appendix_id && <p className='text-xs text-destructive'>{requestForm.errors.regulation_appendix_id}</p>}
                        {requestForm.errors.regulation_appendix_name && <p className='text-xs text-destructive'>{requestForm.errors.regulation_appendix_name}</p>}
                    </div>

                    <div className='space-y-1.5'>
                        <Label>Parameter <span className='text-destructive'>*</span></Label>
                        <ComboboxDropdown
                            value={requestForm.data.requested_parameter_id || requestForm.data.requested_parameter_name || undefined}
                            onValueChange={(value) => {
                                const nextValue = value ?? ''
                                const selected = parameterOptions.find((item) => String(item.id) === nextValue)

                                if (selected) {
                                    requestForm.setData('requested_parameter_id', nextValue)
                                    requestForm.setData('requested_parameter_name', '')

                                    return
                                }

                                requestForm.setData('requested_parameter_id', '')
                                requestForm.setData('requested_parameter_name', nextValue)
                            }}
                            options={parameterOptions.map((item) => ({
                                value: String(item.id),
                                label: `${item.code} - ${item.name}`,
                            }))}
                            placeholder='Pilih/ketik parameter...'
                            searchPlaceholder='Cari parameter...'
                            emptyText='Parameter tidak ditemukan.'
                            allowCustomOption
                            customOptionLabel='Tambah parameter baru'
                        />
                        {requestForm.errors.requested_parameter_id && <p className='text-xs text-destructive'>{requestForm.errors.requested_parameter_id}</p>}
                        {requestForm.errors.requested_parameter_name && <p className='text-xs text-destructive'>{requestForm.errors.requested_parameter_name}</p>}
                    </div>

                    <div className='space-y-1.5'>
                        <Label>Deskripsi</Label>
                        <Textarea
                            rows={3}
                            value={requestForm.data.description}
                            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => requestForm.setData('description', e.target.value)}
                            placeholder='Deskripsi pengajuan sustain...'
                        />
                    </div>

                    <div className='space-y-1.5'>
                        <Label>Catatan Request</Label>
                        <Textarea
                            rows={3}
                            value={requestForm.data.request_note}
                            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => requestForm.setData('request_note', e.target.value)}
                            placeholder='Catatan tambahan untuk reviewer...'
                        />
                    </div>

                    <div className='flex justify-end gap-2'>
                        <Button type='button' variant='outline' onClick={() => setIsRequestDrawerOpen(false)} disabled={requestForm.processing}>
                            Batal
                        </Button>
                        <Button type='submit' disabled={requestForm.processing}>
                            {requestForm.processing ? 'Menyimpan...' : 'Ajukan'}
                        </Button>
                    </div>
                </form>
            </ResizableDrawer>

            <ResizableDrawer
                open={isRejectDrawerOpen}
                onOpenChange={setIsRejectDrawerOpen}
                title='Tolak Permintaan'
                description={selectedRejectItem ? `Request ${selectedRejectItem.request_number}` : 'Masukkan alasan penolakan.'}
            >
                <div className='space-y-4'>
                    <div className='space-y-1.5'>
                        <Label>Catatan Penolakan</Label>
                        <Textarea
                            rows={4}
                            value={rejectNote}
                            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setRejectNote(e.target.value)}
                            placeholder='Jelaskan alasan penolakan...'
                        />
                    </div>
                    <div className='flex justify-end gap-2'>
                        <Button type='button' variant='outline' onClick={() => setIsRejectDrawerOpen(false)}>
                            Batal
                        </Button>
                        <Button type='button' variant='destructive' onClick={submitReject}>
                            Konfirmasi Reject
                        </Button>
                    </div>
                </div>
            </ResizableDrawer>
        </LimsAppLayout>
    )
}
