import { Head, router } from '@inertiajs/react'
import { useState } from 'react'
import { toast } from 'sonner'
import { LimsAppLayout } from '@/layouts/lims-app-layout'
import { Badge } from '@ui/components/ui/badge'
import { Button } from '@ui/components/ui/button'
import { Input } from '@ui/components/ui/input'
import { Pencil, Plus, Search, ToggleLeft, ToggleRight } from 'lucide-react'
import { ResizableDrawer } from '@/components/common/ResizableDrawer'
import { DeleteConfirmationDialog } from '@/components/common/DeleteConfirmationDialog'
import { ToggleStatusDialog } from '@/components/common/ToggleStatusDialog'
import { TestConfigurationTabs } from '@/components/master-data/TestConfigurationTabs'
import { type TestTemplate } from '@/types/glims'
import { TestTemplateForm } from './components/TestTemplateForm'

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

interface RegulationOption extends OptionSimple {
    short_name?: string | null
}

interface AppendixOption extends OptionSimple {
    regulation_id: number
    appendix_number?: string | null
}

interface Paginated<T> {
    data: T[]
    current_page: number
    last_page: number
    per_page: number
    total: number
    from?: number | null
    to?: number | null
}

interface Props {
    testTemplates: Paginated<TestTemplate>
    filters: Record<string, string | undefined>
    sampleTypeOptions: OptionSimple[]
    regulationOptions: RegulationOption[]
    appendixOptions: AppendixOption[]
    parameterOptions: OptionSimple[]
}

function routes(testTemplate?: TestTemplate) {
    const base = '/master-data/test-templates'
    return {
        index: base,
        destroy: testTemplate ? `${base}/${testTemplate.id}` : base,
        toggle: testTemplate ? `${base}/${testTemplate.id}/toggle-status` : base,
        parameters: testTemplate ? `${base}/${testTemplate.id}/parameters` : base,
    }
}

export default function TestTemplateIndex({
    testTemplates,
    filters,
    sampleTypeOptions,
    regulationOptions,
    appendixOptions,
    parameterOptions,
}: Props) {
    const [search, setSearch] = useState(filters.search ?? '')
    const [isDrawerOpen, setIsDrawerOpen] = useState(false)
    const [selectedItem, setSelectedItem] = useState<TestTemplate | undefined>()
    const [isDeleteOpen, setIsDeleteOpen] = useState(false)
    const [itemToDelete, setItemToDelete] = useState<TestTemplate | undefined>()
    const [isToggleOpen, setIsToggleOpen] = useState(false)
    const [itemToToggle, setItemToToggle] = useState<TestTemplate | undefined>()
    const [isDeleting, setIsDeleting] = useState(false)
    const [isToggling, setIsToggling] = useState(false)

    const filteredAppendixOptions = filters.regulation_id
        ? appendixOptions.filter((item) => String(item.regulation_id) === String(filters.regulation_id))
        : appendixOptions

    function applyFilters(next: Record<string, string | number | undefined>) {
        router.get(routes().index, next, { preserveState: true, replace: true })
    }

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

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

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

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

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

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

    return (
        <LimsAppLayout>
            <Head title='Konfigurasi Uji - Template Uji' />
            <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'>Konfigurasi Uji</h1>
                        <p className='text-sm text-muted-foreground'>Kelola grouping/paket, baku mutu, dan template uji dalam satu modul.</p>
                    </div>
                    <Button className='gap-2' onClick={handleCreate}>
                        <Plus className='h-4 w-4' /> Tambah
                    </Button>
                </div>

                <TestConfigurationTabs />

                <div className='rounded-xl border bg-card p-3'>
                    <div className='flex flex-wrap gap-2'>
                        <div className='flex min-w-[260px] flex-1 items-center gap-2'>
                            <Input
                                value={search}
                                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearch(e.target.value)}
                                onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
                                    if (e.key === 'Enter') {
                                        applyFilters({ ...filters, search: search || undefined, page: 1 })
                                    }
                                }}
                                placeholder='Cari template, sampel, regulasi, atau parameter...'
                            />
                            <Button
                                variant='outline'
                                size='icon'
                                onClick={() => applyFilters({ ...filters, search: search || undefined, page: 1 })}
                                title='Cari'
                            >
                                <Search className='h-4 w-4' />
                            </Button>
                        </div>

                        <select
                            value={filters.sample_type_id ?? ''}
                            onChange={(e: React.ChangeEvent<HTMLSelectElement>) => applyFilters({
                                ...filters,
                                sample_type_id: e.target.value || undefined,
                                page: 1,
                            })}
                            className='rounded-md border bg-background px-3 py-1.5 text-sm'
                        >
                            <option value=''>Semua Jenis Sampel</option>
                            {sampleTypeOptions.map((option) => (
                                <option key={option.id} value={option.id}>{option.code} - {option.name}</option>
                            ))}
                        </select>

                        <select
                            value={filters.regulation_id ?? ''}
                            onChange={(e: React.ChangeEvent<HTMLSelectElement>) => applyFilters({
                                ...filters,
                                regulation_id: e.target.value || undefined,
                                regulation_appendix_id: undefined,
                                page: 1,
                            })}
                            className='rounded-md border bg-background px-3 py-1.5 text-sm'
                        >
                            <option value=''>Semua Regulasi</option>
                            {regulationOptions.map((option) => (
                                <option key={option.id} value={option.id}>
                                    {option.short_name ? `${option.short_name} - ${option.name}` : `${option.code} - ${option.name}`}
                                </option>
                            ))}
                        </select>

                        <select
                            value={filters.regulation_appendix_id ?? ''}
                            onChange={(e: React.ChangeEvent<HTMLSelectElement>) => applyFilters({
                                ...filters,
                                regulation_appendix_id: e.target.value || undefined,
                                page: 1,
                            })}
                            className='rounded-md border bg-background px-3 py-1.5 text-sm'
                        >
                            <option value=''>Semua Lampiran</option>
                            {filteredAppendixOptions.map((option) => (
                                <option key={option.id} value={option.id}>
                                    {option.appendix_number ? `${option.appendix_number} - ${option.name}` : `${option.code} - ${option.name}`}
                                </option>
                            ))}
                        </select>

                        <select
                            value={filters.parameter_id ?? ''}
                            onChange={(e: React.ChangeEvent<HTMLSelectElement>) => applyFilters({
                                ...filters,
                                parameter_id: e.target.value || undefined,
                                page: 1,
                            })}
                            className='rounded-md border bg-background px-3 py-1.5 text-sm'
                        >
                            <option value=''>Semua Parameter</option>
                            {parameterOptions.map((option) => (
                                <option key={option.id} value={option.id}>{option.name}</option>
                            ))}
                        </select>

                        {([
                            [null, 'Semua'],
                            ['1', 'Aktif'],
                            ['0', 'Nonaktif'],
                        ] as const).map(([value, label]) => (
                            <button
                                key={value ?? 'all'}
                                onClick={() => applyFilters({
                                    ...filters,
                                    is_active: value ?? undefined,
                                    page: 1,
                                })}
                                className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
                                    (filters.is_active ?? null) === value
                                        ? 'bg-teal-600 text-white'
                                        : 'bg-muted text-muted-foreground hover:bg-muted/80'
                                }`}
                            >
                                {label}
                            </button>
                        ))}
                    </div>
                </div>

                {testTemplates.data.length === 0 ? (
                    <div className='rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground'>
                        Belum ada data template uji.
                    </div>
                ) : (
                    <div className='grid grid-cols-1 gap-4'>
                        {testTemplates.data.map((row) => {
                            const listed = (row.params ?? [])
                                .map((item) => item.parameter?.name)
                                .filter(Boolean)
                                .slice(0, 5) as string[]
                            const moreCount = Math.max(0, (row.params_count ?? listed.length) - listed.length)

                            return (
                                <div key={row.id} className='rounded-xl border bg-card p-4 shadow-sm'>
                                    <div className='grid grid-cols-1 gap-3 md:grid-cols-4'>
                                        <div className='rounded-lg bg-slate-50 p-3'>
                                            <p className='text-xs uppercase tracking-wide text-muted-foreground'>Jenis Sampel</p>
                                            <p className='mt-1 font-semibold'>{row.sample_type?.name ?? '-'}</p>
                                            <p className='text-xs text-muted-foreground'>{row.code}</p>
                                        </div>

                                        <div className='rounded-lg bg-emerald-50 p-3'>
                                            <p className='text-xs uppercase tracking-wide text-muted-foreground'>Regulasi</p>
                                            <p className='mt-1 font-semibold'>{row.regulation?.short_name ?? row.regulation?.name ?? 'Tanpa regulasi'}</p>
                                            <p className='text-xs text-muted-foreground'>{row.regulation_appendix?.name ?? 'Tanpa lampiran'}</p>
                                            <div className='mt-2'>
                                                {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>}
                                            </div>
                                        </div>

                                        <div className='rounded-lg bg-amber-50 p-3'>
                                            <p className='text-xs uppercase tracking-wide text-muted-foreground'>Parameter</p>
                                            <div className='mt-1 flex flex-wrap gap-1'>
                                                {listed.length > 0 ? listed.map((name) => (
                                                    <span key={name} className='rounded-full bg-white px-2 py-0.5 text-xs shadow-sm'>
                                                        {name}
                                                    </span>
                                                )) : <span className='text-xs text-muted-foreground'>Belum ada parameter</span>}
                                                {moreCount > 0 && (
                                                    <span className='rounded-full bg-teal-50 px-2 py-0.5 text-xs text-teal-700'>
                                                        +{moreCount} lainnya
                                                    </span>
                                                )}
                                            </div>
                                            <p className='mt-2 text-xs text-muted-foreground'>
                                                Total: {row.params_count ?? 0}
                                                {row.effective_date ? ` • Efektif ${row.effective_date}` : ''}
                                            </p>
                                        </div>

                                        <div className='rounded-lg bg-zinc-50 p-3'>
                                            <p className='text-xs uppercase tracking-wide text-muted-foreground'>Aksi</p>
                                            <div className='mt-2 flex flex-wrap gap-2'>
                                                <Button size='sm' variant='outline' className='gap-1' onClick={() => handleToggleClick(row)}>
                                                    {row.is_active ? <ToggleRight className='h-4 w-4 text-emerald-600' /> : <ToggleLeft className='h-4 w-4' />}
                                                    {row.is_active ? 'Nonaktifkan' : 'Aktifkan'}
                                                </Button>
                                                <Button size='sm' variant='outline' className='gap-1' onClick={() => handleEdit(row)}>
                                                    <Pencil className='h-3.5 w-3.5' /> Edit
                                                </Button>
                                                <Button
                                                    size='sm'
                                                    variant='default'
                                                    className='gap-1 bg-teal-600 hover:bg-teal-700'
                                                    onClick={() => router.get(routes(row).parameters)}
                                                >
                                                    Kelola Parameter
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        })}
                    </div>
                )}

                <div className='flex flex-wrap items-center justify-between gap-3 rounded-lg border bg-card px-3 py-2 text-sm'>
                    <div className='text-muted-foreground'>
                        Menampilkan {testTemplates.from ?? 0}-{testTemplates.to ?? testTemplates.data.length} dari {testTemplates.total}
                    </div>
                    <div className='flex items-center gap-2'>
                        <Button
                            variant='outline'
                            size='sm'
                            disabled={testTemplates.current_page <= 1}
                            onClick={() => applyFilters({ ...filters, page: testTemplates.current_page - 1 })}
                        >
                            Sebelumnya
                        </Button>
                        <span className='text-muted-foreground'>Hal {testTemplates.current_page} / {testTemplates.last_page}</span>
                        <Button
                            variant='outline'
                            size='sm'
                            disabled={testTemplates.current_page >= testTemplates.last_page}
                            onClick={() => applyFilters({ ...filters, page: testTemplates.current_page + 1 })}
                        >
                            Berikutnya
                        </Button>
                    </div>
                </div>
            </div>

            <ResizableDrawer
                open={isDrawerOpen}
                onOpenChange={setIsDrawerOpen}
                title={selectedItem ? 'Edit Template Uji' : 'Tambah Template Uji'}
                description={selectedItem ? `Edit data: ${selectedItem.name}` : 'Isi form untuk menambah template uji baru'}
            >
                <TestTemplateForm
                    testTemplate={selectedItem}
                    sampleTypeOptions={sampleTypeOptions}
                    regulationOptions={regulationOptions}
                    appendixOptions={appendixOptions}
                    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>
    )
}
