import { Head, router } from '@inertiajs/react'
import { useState } from 'react'
import { Plus, Pencil, ToggleLeft, ToggleRight } from 'lucide-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 { ResizableDrawer } from '@/components/common/ResizableDrawer'
import { DeleteConfirmationDialog } from '@/components/common/DeleteConfirmationDialog'
import { ToggleStatusDialog } from '@/components/common/ToggleStatusDialog'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'
import { SampleCollectionCalculationForm } from './components/SampleCollectionCalculationForm'

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

interface CalculationItem {
    id: number
    sample_type_id: number
    quantity?: number | null
    sample_pickup_duration_unit?: 'day' | 'hour_minute' | null
    sample_pickup_duration_value?: number | null
    factor_x?: number | null
    factor_x_duration_minutes?: number | null
    moving_location_duration_minutes?: number | null
    notes?: string | null
    is_active: boolean
    sample_type?: Option
}

interface Props {
    records: ServerPaginatedData<CalculationItem>
    filters: Record<string, string | undefined>
    sampleTypeOptions: Option[]
}

export default function SampleCollectionCalculationIndex({ records, filters, sampleTypeOptions }: Props) {
    const formatMinutes = (value?: number | null): string => {
        if (value == null || value <= 0) {
            return '-'
        }

        const h = String(Math.floor(value / 60)).padStart(2, '0')
        const m = String(value % 60).padStart(2, '0')
        return `${h}:${m}`
    }

    const formatPickupDuration = (row: CalculationItem): string => {
        if (!row.sample_pickup_duration_unit || row.sample_pickup_duration_value == null) {
            return '-'
        }

        if (row.sample_pickup_duration_unit === 'day') {
            return `${row.sample_pickup_duration_value} hari`
        }

        return formatMinutes(row.sample_pickup_duration_value)
    }

    const [isDrawerOpen, setIsDrawerOpen] = useState(false)
    const [selectedItem, setSelectedItem] = useState<CalculationItem | undefined>()
    const [isDeleteOpen, setIsDeleteOpen] = useState(false)
    const [itemToDelete, setItemToDelete] = useState<CalculationItem | undefined>()
    const [isToggleOpen, setIsToggleOpen] = useState(false)
    const [itemToToggle, setItemToToggle] = useState<CalculationItem | undefined>()
    const [isDeleting, setIsDeleting] = useState(false)
    const [isToggling, setIsToggling] = useState(false)

    const params: ServerDataTableParams = { page: records.current_page, per_page: records.per_page, search: filters.search }
    const columns: ServerColumnDef<CalculationItem>[] = [
        { key: 'sample_type_id', label: 'Sample Type', render: (row) => row.sample_type ? `${row.sample_type.code} - ${row.sample_type.name}` : '-' },
        { key: 'quantity', label: 'Jumlah', render: (row) => row.quantity ?? '-' },
        { key: 'sample_pickup_duration_value', label: 'Durasi Pengambilan', render: (row) => formatPickupDuration(row) },
        { key: 'factor_x', label: 'Faktor X', render: (row) => row.factor_x ?? '-' },
        { key: 'factor_x_duration_minutes', label: 'Durasi Faktor X', render: (row) => formatMinutes(row.factor_x_duration_minutes) },
        { key: 'moving_location_duration_minutes', label: 'Durasi Moving Lokasi', render: (row) => formatMinutes(row.moving_location_duration_minutes) },
        { key: 'is_active', label: 'Status', render: (row) => row.is_active ? <Badge className='bg-emerald-600 text-white'>Aktif</Badge> : <Badge className='border-rose-200 bg-rose-100 text-rose-700'>Nonaktif</Badge> },
        {
            key: 'actions',
            label: '',
            className: 'w-28 text-right',
            render: (row) => (
                <div className='flex justify-end gap-1'>
                    <Button size='icon' variant='ghost' className='h-7 w-7' onClick={() => { setItemToToggle(row); setIsToggleOpen(true) }}>
                        {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' onClick={() => { setSelectedItem(row); setIsDrawerOpen(true) }}>
                        <Pencil className='h-3.5 w-3.5' />
                    </Button>
                </div>
            ),
        },
    ]

    return (
        <LimsAppLayout>
            <Head title='Master Kalkulasi Ambil Sampel' />
            <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'>Master Kalkulasi Ambil Sampel</h1>
                        <p className='text-sm text-muted-foreground'>Kelola aturan kalkulasi pengambilan sampel berdasarkan sample type</p>
                    </div>
                    <Button className='gap-2' onClick={() => { setSelectedItem(undefined); setIsDrawerOpen(true) }}>
                        <Plus className='h-4 w-4' /> Tambah
                    </Button>
                </div>
                <div className='flex flex-wrap gap-2'>
                    <div className='w-full sm:w-[280px]'>
                        <ComboboxDropdown
                            value={filters.sample_type_id || undefined}
                            onValueChange={(value) => router.get('/master-data/sample-collection-calculations', { ...filters, sample_type_id: value || undefined, page: 1 }, { preserveState: true, replace: true })}
                            placeholder='Semua Sample Type'
                            options={sampleTypeOptions.map((o) => ({ value: String(o.id), label: `${o.code} - ${o.name}` }))}
                            searchPlaceholder='Cari sample type...'
                            emptyText='Sample type tidak ditemukan.'
                        />
                    </div>
                </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('/master-data/sample-collection-calculations', { ...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>
                <ServerDataTable
                    data={records}
                    columns={columns}
                    params={params}
                    onParamsChange={(next) => router.get('/master-data/sample-collection-calculations', { ...filters, ...next } as Record<string, string | number | undefined>, { preserveState: true, replace: true })}
                    searchPlaceholder='Cari sample type...'
                    emptyText='Belum ada data kalkulasi ambil sampel.'
                />
            </div>

            <ResizableDrawer open={isDrawerOpen} onOpenChange={setIsDrawerOpen} title={selectedItem ? 'Edit Kalkulasi Ambil Sampel' : 'Tambah Kalkulasi Ambil Sampel'}>
                <SampleCollectionCalculationForm
                    item={selectedItem}
                    sampleTypeOptions={sampleTypeOptions}
                    onSuccess={() => setIsDrawerOpen(false)}
                    onCancel={() => setIsDrawerOpen(false)}
                />
            </ResizableDrawer>

            <DeleteConfirmationDialog
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={() => {
                    if (!itemToDelete) return
                    router.delete(`/master-data/sample-collection-calculations/${itemToDelete.id}`, {
                        onStart: () => setIsDeleting(true),
                        onSuccess: () => { toast.success('Kalkulasi ambil sampel dihapus.'); setIsDeleteOpen(false); setItemToDelete(undefined) },
                        onFinish: () => setIsDeleting(false),
                    })
                }}
                itemName={itemToDelete?.sample_type?.name}
                isDeleting={isDeleting}
            />

            <ToggleStatusDialog
                open={isToggleOpen}
                onOpenChange={setIsToggleOpen}
                onConfirm={() => {
                    if (!itemToToggle) return
                    router.patch(`/master-data/sample-collection-calculations/${itemToToggle.id}/toggle-status`, {}, {
                        onStart: () => setIsToggling(true),
                        onSuccess: () => { toast.success('Status kalkulasi ambil sampel diubah.'); setIsToggleOpen(false); setItemToToggle(undefined) },
                        onFinish: () => setIsToggling(false),
                    })
                }}
                itemName={itemToToggle?.sample_type?.name}
                isActive={itemToToggle?.is_active ?? true}
                isLoading={isToggling}
            />
        </LimsAppLayout>
    )
}
