import { Head, router } from '@inertiajs/react'
import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { LimsAppLayout } from '@/layouts/lims-app-layout'
import { Button } from '@ui/components/ui/button'
import { Input } from '@ui/components/ui/input'
import { Plus, Search, ChevronRight, GripVertical, ToggleLeft, ToggleRight } from 'lucide-react'
import { ResizableDrawer } from '@/components/common/ResizableDrawer'
import { DeleteConfirmationDialog } from '@/components/common/DeleteConfirmationDialog'
import { ToggleStatusDialog } from '@/components/common/ToggleStatusDialog'
import { type QualityStandard } from '@/types/glims'
import { QualityStandardParamForm } from './components/QualityStandardParamForm'

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

interface RegulationOption extends OptionSimple {
    short_name?: 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 {
    qualityStandards: Paginated<QualityStandard>
    filters: Record<string, string | undefined>
    parameterOptions: OptionSimple[]
    unitOptions: { id: number; name: string }[]
}

function getInitialQueryValue(key: string, fallback?: string): string {
    if (fallback && fallback !== '') return fallback
    if (typeof window === 'undefined') return ''
    return new URLSearchParams(window.location.search).get(key) ?? ''
}

function getInitialQueryNumber(key: string, fallback?: string): number | null {
    const raw = getInitialQueryValue(key, fallback)
    if (!raw) return null
    const parsed = Number(raw)
    return Number.isFinite(parsed) ? parsed : null
}

function routes(qualityStandard?: QualityStandard) {
    const base = '/master-data/quality-standards'
    return {
        parameters: qualityStandard ? `${base}/${qualityStandard.id}/parameters` : base,
    }
}

export default function QualityStandardIndex({
    qualityStandards,
    filters,
    parameterOptions,
    unitOptions,
}: Props) {
    const [searchSample, setSearchSample] = useState(() => getInitialQueryValue('qs_search_sample', filters.qs_search_sample))
    const [searchRegulation, setSearchRegulation] = useState(() => getInitialQueryValue('qs_search_regulation', filters.qs_search_regulation))
    const [searchAppendix, setSearchAppendix] = useState(() => getInitialQueryValue('qs_search_appendix', filters.qs_search_appendix))
    const [searchParameter, setSearchParameter] = useState(() => getInitialQueryValue('qs_search_parameter', filters.qs_search_parameter))

    const [selectedSampleId, setSelectedSampleId] = useState<number | null>(() => getInitialQueryNumber('qs_sample_type_id', filters.qs_sample_type_id))
    const [selectedRegulationId, setSelectedRegulationId] = useState<number | null>(() => getInitialQueryNumber('qs_regulation_id', filters.qs_regulation_id))
    const [selectedAppendixKey, setSelectedAppendixKey] = useState<string | null>(() => getInitialQueryValue('qs_appendix_key', filters.qs_appendix_key) || null)

    const [isParamDeleteOpen, setIsParamDeleteOpen] = useState(false)
    const [paramToDelete, setParamToDelete] = useState<{ standardId: number; id: number; name: string } | undefined>()
    const [isParamToggleOpen, setIsParamToggleOpen] = useState(false)
    const [paramToToggle, setParamToToggle] = useState<{ standardId: number; id: number; name: string; isActive: boolean } | undefined>()
    const [isParamDrawerOpen, setIsParamDrawerOpen] = useState(false)
    const [selectedParam, setSelectedParam] = useState<NonNullable<QualityStandard['params']>[number] | undefined>()
    const [selectedStandardForDrawer, setSelectedStandardForDrawer] = useState<QualityStandard | undefined>()
    const [isParamDeleting, setIsParamDeleting] = useState(false)
    const [isParamToggling, setIsParamToggling] = useState(false)
    const [dragParamIndex, setDragParamIndex] = useState<number | null>(null)
    const [isReorderingParam, setIsReorderingParam] = useState(false)

    const allRows = qualityStandards.data

    const sampleItems = useMemo(() => {
        const map = new Map<number, OptionSimple>()
        allRows.forEach((row) => {
            if (row.sample_type?.id) {
                map.set(row.sample_type.id, {
                    id: row.sample_type.id,
                    code: row.sample_type.code,
                    name: row.sample_type.name,
                })
            }
        })

        return [...map.values()]
            .filter((item) => item.name.toLowerCase().includes(searchSample.toLowerCase()) || item.code.toLowerCase().includes(searchSample.toLowerCase()))
            .sort((a, b) => a.name.localeCompare(b.name))
    }, [allRows, searchSample])

    const rowsBySample = useMemo(
        () => allRows.filter((row) => selectedSampleId !== null && row.sample_type?.id === selectedSampleId),
        [allRows, selectedSampleId]
    )

    const regulationItems = useMemo(() => {
        const map = new Map<number, RegulationOption>()
        rowsBySample.forEach((row) => {
            if (row.regulation?.id) {
                map.set(row.regulation.id, {
                    id: row.regulation.id,
                    code: row.regulation.code,
                    name: row.regulation.name,
                    short_name: row.regulation.short_name ?? null,
                })
            }
        })
        return [...map.values()]
            .filter((item) => `${item.short_name ?? ''} ${item.name} ${item.code}`.toLowerCase().includes(searchRegulation.toLowerCase()))
            .sort((a, b) => a.name.localeCompare(b.name))
    }, [rowsBySample, searchRegulation])

    const rowsByRegulation = useMemo(
        () => rowsBySample.filter((row) => selectedRegulationId !== null && row.regulation?.id === selectedRegulationId),
        [rowsBySample, selectedRegulationId]
    )

    const appendixItems = useMemo(() => {
        const map = new Map<string, { key: string; id: number | null; name: string; label: string }>()

        rowsByRegulation.forEach((row) => {
            const id = row.regulation_appendix?.id ?? null
            const key = id === null ? 'none' : String(id)
            const name = row.regulation_appendix?.name ?? 'Tanpa lampiran'
            const label = row.regulation_appendix?.appendix_number
                ? `${row.regulation_appendix.appendix_number} - ${name}`
                : name

            map.set(key, { key, id, name, label })
        })

        return [...map.values()]
            .filter((item) => item.label.toLowerCase().includes(searchAppendix.toLowerCase()))
            .sort((a, b) => a.label.localeCompare(b.label))
    }, [rowsByRegulation, searchAppendix])

    const selectedStandard = useMemo(() => {
        if (selectedAppendixKey === null) return undefined
        return rowsByRegulation.find((row) => {
            const key = row.regulation_appendix?.id ? String(row.regulation_appendix.id) : 'none'
            return key === selectedAppendixKey
        })
    }, [rowsByRegulation, selectedAppendixKey])

    const parameterItems = useMemo(() => {
        const params = selectedStandard?.params ?? []
        return params.filter((param) => {
            const haystack = `${param.parameter?.name ?? ''} ${param.unit ?? ''} ${param.threshold_display ?? ''}`.toLowerCase()
            return haystack.includes(searchParameter.toLowerCase())
        })
    }, [selectedStandard, searchParameter])

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

        const params = new URLSearchParams(window.location.search)
        const setOrDelete = (key: string, value: string | null) => {
            if (value && value.trim() !== '') {
                params.set(key, value)
                return
            }
            params.delete(key)
        }

        setOrDelete('qs_search_sample', searchSample)
        setOrDelete('qs_search_regulation', searchRegulation)
        setOrDelete('qs_search_appendix', searchAppendix)
        setOrDelete('qs_search_parameter', searchParameter)
        setOrDelete('qs_sample_type_id', selectedSampleId !== null ? String(selectedSampleId) : null)
        setOrDelete('qs_regulation_id', selectedRegulationId !== null ? String(selectedRegulationId) : null)
        setOrDelete('qs_appendix_key', selectedAppendixKey)

        const query = params.toString()
        const next = query ? `${window.location.pathname}?${query}` : window.location.pathname
        window.history.replaceState(window.history.state, '', next)
    }, [
        searchSample,
        searchRegulation,
        searchAppendix,
        searchParameter,
        selectedSampleId,
        selectedRegulationId,
        selectedAppendixKey,
    ])

    useEffect(() => {
        if (selectedSampleId === null) {
            if (selectedRegulationId !== null) setSelectedRegulationId(null)
            if (selectedAppendixKey !== null) setSelectedAppendixKey(null)
            return
        }

        const exists = regulationItems.some((item) => item.id === selectedRegulationId)
        if (!exists && selectedRegulationId !== null) {
            setSelectedRegulationId(null)
            setSelectedAppendixKey(null)
        }
    }, [selectedSampleId, regulationItems, selectedRegulationId])

    useEffect(() => {
        if (selectedRegulationId === null) {
            if (selectedAppendixKey !== null) setSelectedAppendixKey(null)
            return
        }

        const exists = appendixItems.some((item) => item.key === selectedAppendixKey)
        if (!exists && selectedAppendixKey !== null) {
            setSelectedAppendixKey(null)
        }
    }, [selectedRegulationId, appendixItems, selectedAppendixKey])

    const selectedSample = sampleItems.find((item) => item.id === selectedSampleId)
    const selectedRegulation = regulationItems.find((item) => item.id === selectedRegulationId)
    const selectedAppendix = appendixItems.find((item) => item.key === selectedAppendixKey)

    function handleCreateStandard() {
        if (!selectedSample || !selectedRegulation) {
            toast.error('Pilih jenis sampel dan regulasi terlebih dahulu.')
            return
        }

        const appendixId = selectedAppendix?.id ?? null
        const appendixCode = selectedAppendix?.id ? String(selectedAppendix.id) : 'NONE'
        const autoCode = `QS-${selectedSample.code}-${selectedRegulation.code}-${appendixCode}`.toUpperCase()
        const autoName = `Baku Mutu ${selectedSample.name} - ${selectedRegulation.short_name ?? selectedRegulation.name}${selectedAppendix?.label ? ` - ${selectedAppendix.label}` : ''}`

        router.post(
            '/master-data/quality-standards',
            {
                sample_type_id: selectedSample.id,
                regulation_id: selectedRegulation.id,
                regulation_appendix_id: appendixId,
                code: autoCode,
                name: autoName,
                effective_date: null,
                description: null,
                is_active: true,
            },
            {
                preserveScroll: true,
                onSuccess: () => toast.success('Baku mutu berhasil dibuat. Lanjutkan isi parameter.'),
                onError: (errorBag) => toast.error(Object.values(errorBag)[0] ?? 'Terjadi kesalahan.'),
            }
        )
    }

    function handleCreateParam() {
        if (!selectedStandard) {
            toast.error('Pilih baku mutu dulu.')
            return
        }

        setSelectedStandardForDrawer(selectedStandard)
        setSelectedParam(undefined)
        setIsParamDrawerOpen(true)
    }

    function handleEditParam(param: NonNullable<QualityStandard['params']>[number]) {
        if (!selectedStandard) {
            return
        }

        setSelectedStandardForDrawer(selectedStandard)
        setSelectedParam(param)
        setIsParamDrawerOpen(true)
    }

    function handleDeleteParamClick(param: NonNullable<QualityStandard['params']>[number]) {
        if (!selectedStandard) {
            return
        }
        setParamToDelete({
            standardId: selectedStandard.id,
            id: param.id,
            name: param.parameter?.name ?? `#${param.id}`,
        })
        setIsParamDeleteOpen(true)
    }

    function handleToggleParamClick(param: NonNullable<QualityStandard['params']>[number]) {
        if (!selectedStandard) {
            return
        }
        const isActive = !(param.deleted_at ?? null)
        setParamToToggle({
            standardId: selectedStandard.id,
            id: param.id,
            name: param.parameter?.name ?? `#${param.id}`,
            isActive,
        })
        setIsParamToggleOpen(true)
    }

    function handleDeleteParamConfirm() {
        if (!paramToDelete) return
        router.delete(`/master-data/quality-standards/${paramToDelete.standardId}/parameters/${paramToDelete.id}`, {
            onStart: () => setIsParamDeleting(true),
            onSuccess: () => {
                toast.success(`Parameter "${paramToDelete.name}" berhasil dihapus.`)
                setIsParamDeleteOpen(false)
                setParamToDelete(undefined)
            },
            onError: () => toast.error('Terjadi kesalahan. Silakan coba lagi.'),
            onFinish: () => setIsParamDeleting(false),
        })
    }

    function handleToggleParamConfirm() {
        if (!paramToToggle) return
        router.patch(`/master-data/quality-standards/${paramToToggle.standardId}/parameters/${paramToToggle.id}/toggle-status`, {}, {
            onStart: () => setIsParamToggling(true),
            onSuccess: () => {
                toast.success(`Parameter "${paramToToggle.name}" berhasil ${paramToToggle.isActive ? 'dinonaktifkan' : 'diaktifkan'}.`)
                setIsParamToggleOpen(false)
                setParamToToggle(undefined)
            },
            onError: () => toast.error('Terjadi kesalahan. Silakan coba lagi.'),
            onFinish: () => setIsParamToggling(false),
        })
    }

    function persistParameterOrder(next: NonNullable<QualityStandard['params']>) {
        if (!selectedStandard) {
            return
        }

        const orderedIds = next.map((item) => item.id)
        router.patch(`/master-data/quality-standards/${selectedStandard.id}/parameters/reorder`, { ordered_ids: orderedIds }, {
            preserveScroll: true,
            onStart: () => setIsReorderingParam(true),
            onSuccess: () => toast.success('Urutan parameter diperbarui.'),
            onError: () => toast.error('Gagal menyimpan urutan parameter.'),
            onFinish: () => setIsReorderingParam(false),
        })
    }

    function handleDropParam(targetIndex: number) {
        if (dragParamIndex === null || dragParamIndex === targetIndex || !selectedStandard) {
            setDragParamIndex(null)
            return
        }

        // Reorder aman hanya saat tidak difilter, agar urutan penuh tidak ambigu.
        if (searchParameter.trim() !== '') {
            setDragParamIndex(null)
            toast.error('Kosongkan pencarian parameter dulu untuk mengubah urutan.')
            return
        }

        const fullParams = (selectedStandard.params ?? []).slice().sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
        const next = [...fullParams]
        const [moved] = next.splice(dragParamIndex, 1)
        next.splice(targetIndex, 0, moved)
        const normalized = next.map((item, idx) => ({ ...item, sort_order: idx + 1 }))
        setDragParamIndex(null)
        persistParameterOrder(normalized)
    }

    return (
        <LimsAppLayout>
            <Head title='Baku Mutu' />
            <div className='flex h-full flex-1 flex-col gap-4 p-4'>
                <div>
                    <h1 className='text-xl font-bold tracking-tight'>Baku Mutu</h1>
                    <p className='text-sm text-muted-foreground'>Kelola jenis sampel, regulasi, lampiran, dan parameter uji dengan baku mutu.</p>
                </div>

                <div className='flex flex-wrap gap-2'>
                    {([
                        [null, 'Semua'],
                        ['1', 'Aktif'],
                        ['0', 'Nonaktif'],
                    ] as const).map(([v, label]) => (
                        <button
                            key={v ?? 'all'}
                            onClick={() => router.get(
                                '/master-data/quality-standards',
                                { ...filters, is_active: v ?? undefined, page: 1 },
                                { preserveState: true, replace: 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='flex flex-wrap items-center justify-end gap-2'>
                    {selectedStandard ? (
                        <>
                            <Button className='gap-2' onClick={handleCreateParam}>
                                <Plus className='h-4 w-4' /> Tambah Parameter
                            </Button>
                            <Button variant='outline' onClick={() => router.get(routes(selectedStandard).parameters)}>
                                Halaman Penuh
                            </Button>
                        </>
                    ) : (
                        <Button className='gap-2' onClick={handleCreateStandard}>
                            <Plus className='h-4 w-4' /> Tambah Baku Mutu
                        </Button>
                    )}
                </div>

                <div className='grid grid-cols-1 overflow-hidden rounded-xl border bg-card xl:grid-cols-4'>
                    <div className='border-b p-4 xl:border-b-0 xl:border-r'>
                        <div className='mb-3 flex items-center justify-between'>
                            <h2 className='text-xs font-semibold'>Jenis Sampel</h2>
                        </div>
                        <div className='relative mb-3'>
                            <Search className='absolute left-3 top-3 h-4 w-4 text-muted-foreground' />
                            <Input className='pl-9' placeholder='Cari...' value={searchSample} onChange={(e) => setSearchSample(e.target.value)} />
                        </div>
                        <div className='space-y-2'>
                            {sampleItems.map((item) => {
                                const active = item.id === selectedSampleId
                                return (
                                    <button
                                        key={item.id}
                                        type='button'
                                        onClick={() => {
                                            setSelectedSampleId(item.id)
                                            setSelectedRegulationId(null)
                                            setSelectedAppendixKey(null)
                                        }}
                                        className={`w-full rounded-xl border p-3 text-left transition ${active ? 'border-blue-600 bg-blue-600 text-white' : 'bg-background hover:bg-muted/40'}`}
                                    >
                                        <div className='flex items-center justify-between gap-2'>
                                            <div>
                                                <p className='text-xs font-semibold leading-tight'>{item.name}</p>
                                                <p className={`text-sm ${active ? 'text-blue-100' : 'text-muted-foreground'}`}>{item.code}</p>
                                            </div>
                                            <ChevronRight className='h-5 w-5' />
                                        </div>
                                    </button>
                                )
                            })}
                        </div>
                    </div>

                    <div className='border-b p-4 xl:border-b-0 xl:border-r'>
                        <div className='mb-3'>
                            <h2 className='text-xs font-semibold'>Regulasi</h2>
                            <p className='text-sm text-muted-foreground'>untuk {selectedSample?.name ?? '-'}</p>
                        </div>
                        <div className='relative mb-3'>
                            <Search className='absolute left-3 top-3 h-4 w-4 text-muted-foreground' />
                            <Input className='pl-9' placeholder='Cari...' value={searchRegulation} onChange={(e) => setSearchRegulation(e.target.value)} />
                        </div>
                        <div className='space-y-2'>
                            {regulationItems.map((item) => {
                                const active = item.id === selectedRegulationId
                                return (
                                    <button
                                        key={item.id}
                                        type='button'
                                        onClick={() => {
                                            setSelectedRegulationId(item.id)
                                            setSelectedAppendixKey(null)
                                        }}
                                        className={`w-full rounded-xl border p-3 text-left transition ${active ? 'border-blue-600 bg-blue-600 text-white' : 'bg-background hover:bg-muted/40'}`}
                                    >
                                        <div className='flex items-center justify-between gap-2'>
                                            <div>
                                                <p className='text-xs font-semibold leading-tight'>{item.short_name ?? item.name}</p>
                                                <p className={`text-sm ${active ? 'text-blue-100' : 'text-muted-foreground'}`}>{item.code}</p>
                                            </div>
                                            <ChevronRight className='h-5 w-5' />
                                        </div>
                                    </button>
                                )
                            })}
                            {selectedSampleId === null && <p className='text-xs text-muted-foreground'>Pilih jenis sampel dulu.</p>}
                            {selectedSampleId !== null && regulationItems.length === 0 && <p className='text-xs text-muted-foreground'>Tidak ada regulasi terhubung.</p>}
                        </div>
                    </div>

                    <div className='border-b p-4 xl:border-b-0 xl:border-r'>
                        <div className='mb-3'>
                            <h2 className='text-xs font-semibold'>Lampiran</h2>
                            <p className='text-sm text-muted-foreground'>dari {selectedRegulation?.short_name ?? selectedRegulation?.name ?? '-'}</p>
                        </div>
                        <div className='relative mb-3'>
                            <Search className='absolute left-3 top-3 h-4 w-4 text-muted-foreground' />
                            <Input className='pl-9' placeholder='Cari...' value={searchAppendix} onChange={(e) => setSearchAppendix(e.target.value)} />
                        </div>
                        <div className='space-y-2'>
                            {appendixItems.map((item) => {
                                const active = item.key === selectedAppendixKey
                                return (
                                    <button
                                        key={item.key}
                                        type='button'
                                        onClick={() => setSelectedAppendixKey(item.key)}
                                        className={`w-full rounded-xl border p-3 text-left transition ${active ? 'border-blue-600 bg-blue-600 text-white' : 'bg-background hover:bg-muted/40'}`}
                                    >
                                        <div className='flex items-center justify-between gap-2'>
                                            <div>
                                                <p className='text-xs font-semibold leading-tight'>{item.label}</p>
                                            </div>
                                            <ChevronRight className='h-5 w-5' />
                                        </div>
                                    </button>
                                )
                            })}
                            {selectedRegulationId === null && <p className='text-xs text-muted-foreground'>Pilih regulasi dulu.</p>}
                            {selectedRegulationId !== null && appendixItems.length === 0 && <p className='text-xs text-muted-foreground'>Tidak ada lampiran untuk regulasi ini.</p>}
                        </div>
                    </div>

                    <div className='p-4'>
                        <div className='mb-3 space-y-2'>
                            <h2 className='text-xs font-semibold'>Parameter</h2>
                            <p className='min-w-0 truncate text-sm text-muted-foreground' title={selectedAppendix?.label ?? '-'}>
                                dari {selectedAppendix?.label ?? '-'}
                            </p>
                        </div>

                        <div className='relative mb-3'>
                            <Search className='absolute left-3 top-3 h-4 w-4 text-muted-foreground' />
                            <Input className='pl-9' placeholder='Cari parameter...' value={searchParameter} onChange={(e) => setSearchParameter(e.target.value)} />
                        </div>

                        <div className='space-y-2'>
                            {parameterItems.map((param) => {
                                // Fallback true bila backend belum kirim status per parameter.
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                const isParamActive = !((param as { deleted_at?: string | null }).deleted_at ?? null)

                                return (
                                <button
                                    key={param.id}
                                    type='button'
                                    draggable={searchParameter.trim() === ''}
                                    onDragStart={() => setDragParamIndex(parameterItems.findIndex((item) => item.id === param.id))}
                                    onDragOver={(e) => e.preventDefault()}
                                    onDrop={() => handleDropParam(parameterItems.findIndex((item) => item.id === param.id))}
                                    className='w-full rounded-xl border bg-background p-3 text-left transition hover:bg-muted/20'
                                    onClick={() => handleEditParam(param)}
                                >
                                    <div className='flex items-center justify-between gap-2'>
                                        <div className='flex items-center gap-2'>
                                            <GripVertical className='h-4 w-4 text-muted-foreground' />
                                            <p className='text-xs font-semibold'>{param.parameter?.name ?? '-'}</p>
                                        </div>
                                        <div className='flex items-center gap-1'>
                                            <Button
                                                type='button'
                                                size='sm'
                                                variant='outline'
                                                className={`h-7 rounded-full px-3 text-sm ${
                                                    isParamActive
                                                        ? 'border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-600'
                                                        : 'border-muted-foreground/30 bg-muted text-foreground hover:bg-muted'
                                                }`}
                                                title={isParamActive ? 'Status parameter: Aktif' : 'Status parameter: Nonaktif'}
                                                onClick={(e) => {
                                                    e.stopPropagation()
                                                    handleToggleParamClick(param)
                                                }}
                                            >
                                                {isParamActive ? 'Aktif' : 'Nonaktif'}
                                            </Button>
                                            <Button
                                                type='button'
                                                size='icon'
                                                variant='ghost'
                                                className={`h-7 w-7 ${
                                                    isParamActive
                                                        ? 'text-emerald-600 hover:text-emerald-700'
                                                        : 'text-muted-foreground hover:text-muted-foreground'
                                                }`}
                                                title={isParamActive ? 'Set nonaktif' : 'Set aktif'}
                                                onClick={(e) => {
                                                    e.stopPropagation()
                                                    handleToggleParamClick(param)
                                                }}
                                            >
                                                {isParamActive ? <ToggleRight className='h-3.5 w-3.5' /> : <ToggleLeft className='h-3.5 w-3.5' />}
                                            </Button>
                                        </div>
                                    </div>
                                    <p className='text-sm text-muted-foreground'>
                                        {param.unit ?? '-'}
                                    </p>
                                    <p className='mt-1 text-sm text-blue-700'>
                                        Baku Mutu: {param.threshold_display ?? `${param.min_value ?? '-'} - ${param.max_value ?? '-'}`}
                                    </p>
                                </button>
                                )
                            })}
                            {selectedStandard && searchParameter.trim() === '' && (
                                <p className='text-xs text-muted-foreground'>Tip: tarik dan lepas card parameter untuk ubah urutan.</p>
                            )}
                            {isReorderingParam && (
                                <p className='text-xs text-muted-foreground'>Menyimpan urutan parameter...</p>
                            )}
                            {selectedStandard && parameterItems.length === 0 && <p className='text-xs text-muted-foreground'>Belum ada parameter pada baku mutu ini.</p>}
                            {!selectedStandard && <p className='text-xs text-muted-foreground'>Pilih lampiran untuk melihat parameter.</p>}
                        </div>
                    </div>
                </div>
            </div>

            <ResizableDrawer
                open={isParamDrawerOpen}
                onOpenChange={setIsParamDrawerOpen}
                title={selectedParam ? 'Edit Parameter Baku Mutu' : 'Tambah Parameter Baku Mutu'}
                description={selectedParam ? `Edit: ${selectedParam.parameter?.name ?? selectedParam.id}` : 'Tambahkan parameter untuk baku mutu ini'}
            >
                {selectedStandardForDrawer ? (
                    <QualityStandardParamForm
                        qualityStandard={selectedStandardForDrawer}
                        parameterOptions={parameterOptions}
                        unitOptions={unitOptions}
                        param={selectedParam}
                        onSuccess={() => setIsParamDrawerOpen(false)}
                        onCancel={() => setIsParamDrawerOpen(false)}
                    />
                ) : (
                    <p className='text-sm text-muted-foreground'>Pilih baku mutu terlebih dahulu.</p>
                )}
            </ResizableDrawer>

            <DeleteConfirmationDialog
                open={isParamDeleteOpen}
                onOpenChange={setIsParamDeleteOpen}
                onConfirm={handleDeleteParamConfirm}
                itemName={paramToDelete?.name}
                isDeleting={isParamDeleting}
            />

            <ToggleStatusDialog
                open={isParamToggleOpen}
                onOpenChange={setIsParamToggleOpen}
                onConfirm={handleToggleParamConfirm}
                itemName={paramToToggle?.name}
                isActive={paramToToggle?.isActive ?? true}
                isLoading={isParamToggling}
            />
        </LimsAppLayout>
    )
}
