import { Head, router } from '@inertiajs/react'
import { useState } from 'react'
import { toast } from 'sonner'
import { LimsAppLayout } from '@/layouts/lims-app-layout'
import { ServerDataTable, type ServerColumnDef, type ServerPaginatedData, type ServerDataTableParams } from '@ui/components/data-table/server-data-table'
import { Button } from '@ui/components/ui/button'
import { Badge } from '@ui/components/ui/badge'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'
import { type Regulation } from '@/types/glims'
import RegulationController from '@/actions/App/Modules/MasterData/Infrastructure/Controllers/RegulationController'
import { Plus, Pencil, ToggleLeft, ToggleRight, FileText, Paperclip } from 'lucide-react'
import { ResizableDrawer } from '@/components/common/ResizableDrawer'
import { DeleteConfirmationDialog } from '@/components/common/DeleteConfirmationDialog'
import { ToggleStatusDialog } from '@/components/common/ToggleStatusDialog'
import { RegulatoryTabs } from '@/components/master-data/RegulatoryTabs'
import { RegulationForm } from './components/RegulationForm'
import { RegulationDetailDrawer } from './components/RegulationDetailDrawer'

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

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

interface Props {
    regulations: ServerPaginatedData<Regulation>
    filters: Record<string, string | undefined>
    replaceRegulationOptions: RegulationOption[]
    sampleTypeOptions: SampleTypeOption[]
}

const STATUS_OPTIONS = [
    { value: 'BERLAKU',  label: 'Berlaku',  color: 'bg-emerald-600' },
    { value: 'DICABUT',  label: 'Dicabut',  color: 'bg-red-600' },
    { value: 'DRAFT',    label: 'Draft',    color: 'bg-amber-500' },
]

function RegulationStatusBadge({ status }: { status: string | null }) {
    if (!status) return <span className='text-muted-foreground'>—</span>
    const found = STATUS_OPTIONS.find(s => s.value === status)
    if (!found) return <Badge variant='outline'>{status}</Badge>
    return <Badge className={`${found.color} text-white`}>{found.label}</Badge>
}

export default function RegulationIndex({ regulations, filters, replaceRegulationOptions, sampleTypeOptions }: Props) {
    const [isDrawerOpen, setIsDrawerOpen]   = useState(false)
    const [selectedItem, setSelectedItem]   = useState<Regulation | undefined>()
    const [isDeleteOpen, setIsDeleteOpen]   = useState(false)
    const [itemToDelete, setItemToDelete]   = useState<Regulation | undefined>()
    const [isToggleOpen, setIsToggleOpen]   = useState(false)
    const [itemToToggle, setItemToToggle]   = useState<Regulation | undefined>()
    const [isDeleting, setIsDeleting]       = useState(false)
    const [isToggling, setIsToggling]       = useState(false)

    // ── Detail drawer state ──────────────────────────────────────────────────
    const [isDetailOpen, setIsDetailOpen]   = useState(false)
    const [detailItem, setDetailItem]       = useState<Regulation | undefined>()
    const [detailTab, setDetailTab]         = useState<'info' | 'lampiran' | 'attachment'>('info')

    function openDetail(item: Regulation, tab: 'info' | 'lampiran' | 'attachment' = 'info') {
        setDetailItem(item)
        setDetailTab(tab)
        setIsDetailOpen(true)
    }

    function handleCreate() {
        setSelectedItem(undefined)
        setIsDrawerOpen(true)
    }

    function handleEdit(item: Regulation) {
        setSelectedItem(item)
        setIsDrawerOpen(true)
    }

    function handleDeleteClick(item: Regulation) {
        setItemToDelete(item)
        setIsDeleteOpen(true)
    }

    function handleToggleClick(item: Regulation) {
        setItemToToggle(item)
        setIsToggleOpen(true)
    }

    function handleDeleteConfirm() {
        if (!itemToDelete) return
        const name = itemToDelete.name
        router.delete(RegulationController.destroy(itemToDelete).url, {
            onStart:   () => setIsDeleting(true),
            onSuccess: () => {
                toast.success(`Regulasi "${name}" berhasil dihapus.`)
                setIsDeleteOpen(false)
                setItemToDelete(undefined)
            },
            onError:   () => toast.error('Terjadi kesalahan. Silakan coba lagi.'),
            onFinish:  () => setIsDeleting(false),
        })
    }

    function handleToggleConfirm() {
        if (!itemToToggle) return
        const name  = itemToToggle.name
        const label = itemToToggle.is_active ? 'dinonaktifkan' : 'diaktifkan'
        router.patch(RegulationController.toggleStatus(itemToToggle).url, {}, {
            onStart:   () => setIsToggling(true),
            onSuccess: () => {
                toast.success(`Regulasi "${name}" berhasil ${label}.`)
                setIsToggleOpen(false)
                setItemToToggle(undefined)
            },
            onError:   () => toast.error('Terjadi kesalahan. Silakan coba lagi.'),
            onFinish:  () => setIsToggling(false),
        })
    }

    function handleFormSuccess() {
        setIsDrawerOpen(false)
    }

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

    const columns: ServerColumnDef<Regulation>[] = [
        {
            key: 'name',
            label: 'Nama Regulasi',
            sortable: true,
            render: (row) => (
                <button
                    className='text-left hover:underline focus:outline-none'
                    onClick={() => openDetail(row, 'info')}
                    type='button'
                >
                    <span className='font-medium text-foreground'>{row.name}</span>
                </button>
            ),
        },
        {
            key: 'regulation_type' as keyof Regulation,
            label: 'Tipe Regulasi',
            className: 'w-36',
            render: (row) => row.regulation_type
                ? <Badge variant='outline'>{row.regulation_type}</Badge>
                : <span className='text-muted-foreground'>—</span>,
        },
        {
            key: 'effective_date',
            label: 'Efektif',
            className: 'w-28 text-center',
            render: (row) => row.effective_date
                ? new Date(row.effective_date).toLocaleDateString('id-ID', { year: 'numeric', month: 'short', day: 'numeric' })
                : <span className='text-muted-foreground'>—</span>,
        },
        {
            // Lampiran count badge — klik langsung buka detail tab Lampiran
            key: 'appendices_count' as keyof Regulation,
            label: 'Lampiran',
            className: 'w-24 text-center',
            render: (row) => (
                <button
                    type='button'
                    title='Lihat lampiran regulasi ini'
                    onClick={() => openDetail(row, 'lampiran')}
                    className='inline-flex items-center gap-1 rounded-full bg-sky-50 px-2.5 py-0.5 text-xs font-semibold text-sky-700 transition-colors hover:bg-sky-100 dark:bg-sky-950/40 dark:text-sky-300'
                >
                    <FileText className='h-3 w-3' />
                    {row.appendices_count ?? '—'}
                </button>
            ),
        },
        {
            // Attachment count badge — klik langsung buka detail tab Attachment
            key: 'attachments_count' as keyof Regulation,
            label: 'Attachment',
            className: 'w-24 text-center',
            render: (row) => (
                <button
                    type='button'
                    title='Lihat attachment regulasi ini'
                    onClick={() => openDetail(row, 'attachment')}
                    className='inline-flex items-center gap-1 rounded-full bg-violet-50 px-2.5 py-0.5 text-xs font-semibold text-violet-700 transition-colors hover:bg-violet-100 dark:bg-violet-950/40 dark:text-violet-300'
                >
                    <Paperclip className='h-3 w-3' />
                    {row.attachments_count ?? '—'}
                </button>
            ),
        },
        {
            key: 'status',
            label: 'Status',
            className: 'w-24',
            render: (row) => <RegulationStatusBadge status={row.status} />,
        },
        {
            key: 'is_active',
            label: 'Aktif',
            className: 'w-20 text-center',
            render: (row) => row.is_active
                ? <Badge variant='default' className='bg-emerald-600'>Aktif</Badge>
                : <Badge className='border-rose-200 bg-rose-100 text-rose-700'>Nonaktif</Badge>,
        },
        {
            key: 'actions',
            label: '',
            className: 'w-24 text-right',
            render: (row) => (
                <div className='flex justify-end gap-1'>
                    <Button
                        size='icon'
                        variant='ghost'
                        className='h-7 w-7'
                        title={row.is_active ? 'Nonaktifkan' : 'Aktifkan'}
                        onClick={() => handleToggleClick(row)}
                    >
                        {row.is_active
                            ? <ToggleRight className='h-4 w-4 text-emerald-600' />
                            : <ToggleLeft className='h-4 w-4 text-muted-foreground' />}
                    </Button>
                    <Button
                        size='icon'
                        variant='ghost'
                        className='h-7 w-7'
                        title='Edit'
                        onClick={() => handleEdit(row)}
                    >
                        <Pencil className='h-3.5 w-3.5' />
                    </Button>
                </div>
            ),
        },
    ]

    return (
        <LimsAppLayout>
            <Head title='Regulasi' />
            <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'>Dokumen Regulasi</h1>
                        <p className='text-sm text-muted-foreground'>
                            Kelola regulasi induk, lampiran, dan attachment acuan
                        </p>
                    </div>
                    <Button className='gap-2' onClick={handleCreate}>
                        <Plus className='h-4 w-4' /> Tambah
                    </Button>
                </div>

                <RegulatoryTabs />

                <div className='flex flex-wrap items-center gap-4'>
                    <div className='w-full sm:w-[240px]'>
                        <ComboboxDropdown
                            value={filters.status || undefined}
                            onValueChange={(value) => router.get(
                                RegulationController.index().url,
                                { ...filters, status: value || undefined, page: 1 },
                                { preserveState: true, replace: true },
                            )}
                            placeholder='Semua Status'
                            options={STATUS_OPTIONS.map((statusOption) => ({
                                value: statusOption.value,
                                label: statusOption.label,
                            }))}
                            searchPlaceholder='Cari status...'
                            emptyText='Status tidak ditemukan.'
                        />
                    </div>

                    <div className='flex flex-wrap gap-2'>
                        {([
                            [null, 'Semua'],
                            ['1',  'Aktif'],
                            ['0',  'Nonaktif'],
                        ] as const).map(([v, label]) => (
                            <button
                                key={v ?? 'all_active'}
                                onClick={() => router.get(RegulationController.index().url, { ...filters, is_active: v ?? undefined }, { preserveState: true })}
                                className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
                                    (filters.is_active ?? null) === v
                                        ? 'bg-teal-600 text-white'
                                        : 'bg-muted text-muted-foreground hover:bg-muted/80'
                                }`}
                            >
                                {label}
                            </button>
                        ))}
                    </div>

                    <div className='ml-auto flex items-center gap-3 text-xs text-muted-foreground'>
                        <span className='flex items-center gap-1'>
                            <FileText className='h-3 w-3 text-sky-500' />
                            klik badge → lihat lampiran
                        </span>
                        <span className='flex items-center gap-1'>
                            <Paperclip className='h-3 w-3 text-violet-500' />
                            klik badge → lihat attachment
                        </span>
                    </div>
                </div>

                <ServerDataTable
                    data={regulations}
                    columns={columns}
                    params={params}
                    onParamsChange={(next) => router.get(
                        RegulationController.index().url,
                        { ...filters, ...next } as Record<string, string | number | undefined>,
                        { preserveState: true, replace: true },
                    )}
                    searchPlaceholder='Cari nama regulasi...'
                    emptyText='Belum ada regulasi.'
                />
            </div>

            {/* ── Edit / Create Drawer ── */}
            <ResizableDrawer
                open={isDrawerOpen}
                onOpenChange={setIsDrawerOpen}
                title={selectedItem ? 'Edit Regulasi' : 'Tambah Regulasi'}
                description={selectedItem ? `Edit data: ${selectedItem.name}` : 'Isi form untuk menambah regulasi baru'}
            >
                <RegulationForm
                    regulation={selectedItem}
                    replaceOptions={replaceRegulationOptions}
                    onSuccess={handleFormSuccess}
                    onCancel={() => setIsDrawerOpen(false)}
                />
            </ResizableDrawer>

            {/* ── Detail View Drawer ── */}
            <RegulationDetailDrawer
                regulation={detailItem}
                open={isDetailOpen}
                onOpenChange={setIsDetailOpen}
                defaultTab={detailTab}
                sampleTypeOptions={sampleTypeOptions}
                onEdit={(item) => { handleEdit(item) }}
                onMutate={() => router.reload({ only: ['regulations'] })}
            />

            <DeleteConfirmationDialog
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDeleteConfirm}
                itemName={itemToDelete?.name}
                isDeleting={isDeleting}
            />

            <ToggleStatusDialog
                open={isToggleOpen}
                onOpenChange={setIsToggleOpen}
                onConfirm={handleToggleConfirm}
                itemName={itemToToggle?.name}
                isActive={itemToToggle?.is_active ?? true}
                isLoading={isToggling}
            />
        </LimsAppLayout>
    )
}


