import { Head, router } from '@inertiajs/react'
import { useMemo, useState } from 'react'
import { toast } from 'sonner'
import { LimsAppLayout } from '@/layouts/lims-app-layout'
import { ServerDataTable, type ServerColumnDef, type ServerDataTableParams, type ServerPaginatedData } 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 { Plus, Pencil, ToggleLeft, ToggleRight, Download } 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 { type RegulationAttachment } from '@/types/glims'
import { RegulationAttachmentForm } from './components/RegulationAttachmentForm'

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

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

interface Props {
    attachments: ServerPaginatedData<RegulationAttachment>
    filters: Record<string, string | undefined>
    regulationOptions: RegulationOption[]
    sampleTypeOptions: SampleTypeOption[]
}

function routes(attachment?: RegulationAttachment) {
    const base = '/master-data/regulation-attachments'
    return {
        index: base,
        destroy: attachment ? `${base}/${attachment.id}` : base,
        toggle: attachment ? `${base}/${attachment.id}/toggle-status` : base,
        download: attachment ? `${base}/${attachment.id}/download` : base,
    }
}

function formatFileSize(size: number | null): string {
    if (size === null || size <= 0) return '-'

    const units = ['B', 'KB', 'MB', 'GB']
    let value = size
    let unitIndex = 0
    while (value >= 1024 && unitIndex < units.length - 1) {
        value /= 1024
        unitIndex += 1
    }

    return `${value.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`
}

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

    const categories = useMemo(() => {
        const all = attachments.data
            .map((item) => item.category)
            .filter((item): item is string => !!item && item.trim().length > 0)
        return Array.from(new Set(all)).sort((a, b) => a.localeCompare(b))
    }, [attachments.data])

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

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

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

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

    function handleDeleteConfirm() {
        if (!itemToDelete) return
        const name = itemToDelete.name

        router.delete(routes(itemToDelete).destroy, {
            onStart: () => setIsDeleting(true),
            onSuccess: () => {
                toast.success(`Attachment "${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(routes(itemToToggle).toggle, {}, {
            onStart: () => setIsToggling(true),
            onSuccess: () => {
                toast.success(`Attachment "${name}" berhasil ${label}.`)
                setIsToggleOpen(false)
                setItemToToggle(undefined)
            },
            onError: () => toast.error('Terjadi kesalahan. Silakan coba lagi.'),
            onFinish: () => setIsToggling(false),
        })
    }

    function handleDownload(item: RegulationAttachment) {
        window.open(routes(item).download, '_blank', 'noopener,noreferrer')
    }

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

    const columns: ServerColumnDef<RegulationAttachment>[] = [
        {
            key: 'name',
            label: 'Nama Dokumen',
            sortable: true,
            render: (row) => (
                <div className='space-y-0.5'>
                    <div className='font-medium'>{row.name}</div>
                    {row.class_name && <div className='text-xs text-muted-foreground'>{row.class_name}</div>}
                </div>
            ),
        },
        {
            key: 'regulation_id',
            label: 'Regulasi',
            render: (row) => row.regulation?.short_name ?? row.regulation?.name ?? <span className='text-muted-foreground'>-</span>,
        },
        {
            key: 'sample_type_id',
            label: 'Jenis Sampel',
            render: (row) => row.sample_type ? `${row.sample_type.code} - ${row.sample_type.name}` : <span className='text-muted-foreground'>Semua</span>,
        },
        {
            key: 'category',
            label: 'Kategori',
            render: (row) => row.category ?? <span className='text-muted-foreground'>-</span>,
        },
        {
            key: 'file_name',
            label: 'File',
            render: (row) => (
                <div className='space-y-0.5'>
                    <div className='text-sm'>{row.file_name}</div>
                    <div className='text-xs text-muted-foreground'>{formatFileSize(row.file_size)}</div>
                </div>
            ),
        },
        {
            key: 'is_active',
            label: 'Status',
            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-36 text-right',
            render: (row) => (
                <div className='flex justify-end gap-1'>
                    <Button
                        size='icon'
                        variant='ghost'
                        className='h-7 w-7'
                        title='Download'
                        onClick={() => handleDownload(row)}
                    >
                        <Download className='h-3.5 w-3.5' />
                    </Button>
                    <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='Attachment 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 gap-2'>
                    <div className='w-full sm:w-[280px]'>
                        <ComboboxDropdown
                            value={filters.regulation_id ?? undefined}
                            onValueChange={(value) => router.get(
                                routes().index,
                                { ...filters, regulation_id: value || undefined, page: 1 },
                                { preserveState: true, replace: true },
                            )}
                            placeholder='Semua Regulasi'
                            options={regulationOptions.map((r) => ({
                                value: String(r.id),
                                label: r.short_name ? `${r.short_name} - ${r.name}` : `${r.code} - ${r.name}`,
                            }))}
                            searchPlaceholder='Cari regulasi...'
                            emptyText='Regulasi tidak ditemukan.'
                        />
                    </div>

                    <div className='w-full sm:w-[280px]'>
                        <ComboboxDropdown
                            value={filters.sample_type_id ?? undefined}
                            onValueChange={(value) => router.get(
                                routes().index,
                                { ...filters, sample_type_id: value || undefined, page: 1 },
                                { preserveState: true, replace: true },
                            )}
                            placeholder='Semua Jenis Sampel'
                            options={sampleTypeOptions.map((s) => ({
                                value: String(s.id),
                                label: `${s.code} - ${s.name}`,
                            }))}
                            searchPlaceholder='Cari jenis sampel...'
                            emptyText='Jenis sampel tidak ditemukan.'
                        />
                    </div>

                    <div className='w-full sm:w-[280px]'>
                        <ComboboxDropdown
                            value={filters.category ?? undefined}
                            onValueChange={(value) => router.get(
                                routes().index,
                                { ...filters, category: value || undefined, page: 1 },
                                { preserveState: true, replace: true },
                            )}
                            placeholder='Semua Kategori'
                            options={categories.map((category) => ({ value: category, label: category }))}
                            searchPlaceholder='Cari kategori...'
                            emptyText='Kategori tidak ditemukan.'
                        />
                    </div>

                    {([
                        [null, 'Semua'],
                        ['1', 'Aktif'],
                        ['0', 'Nonaktif'],
                    ] as const).map(([v, label]) => (
                        <button
                            key={v ?? 'all'}
                            onClick={() => router.get(routes().index, { ...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>

                <ServerDataTable
                    data={attachments}
                    columns={columns}
                    params={params}
                    onParamsChange={(next: Partial<ServerDataTableParams>) => router.get(
                        routes().index,
                        { ...filters, ...next } as Record<string, string | number | undefined>,
                        { preserveState: true, replace: true },
                    )}
                    searchPlaceholder='Cari nama dokumen, kategori, atau nama file...'
                    emptyText='Belum ada attachment regulasi.'
                />
            </div>

            <ResizableDrawer
                open={isDrawerOpen}
                onOpenChange={setIsDrawerOpen}
                title={selectedItem ? 'Edit Attachment Regulasi' : 'Tambah Attachment Regulasi'}
                description={selectedItem ? `Edit data: ${selectedItem.name}` : 'Upload file acuan regulasi baru'}
            >
                <RegulationAttachmentForm
                    attachment={selectedItem}
                    regulationOptions={regulationOptions}
                    sampleTypeOptions={sampleTypeOptions}
                    onSuccess={() => setIsDrawerOpen(false)}
                    onCancel={() => setIsDrawerOpen(false)}
                />
            </ResizableDrawer>

            <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>
    )
}
