import { Link, router } from '@inertiajs/react';
import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { ConfirmActionDialog } from '@/components/confirm-action-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useSyncedState } from '@/hooks/use-synced-state';
import { formatEmployeeJoiningDateNumericOrDash } from '@/lib/dates';

/**
 * @param {object} props
 * @param {import('@inertiajs/core').Paginator<any>} props.applications
 * @param {object} props.filters
 * @param {Record<string, string>} props.labels
 * @param {(opts?: object) => string} props.indexUrl
 * @param {(id: number) => string} props.editUrl
 * @param {(id: number) => string} props.destroyUrl
 * @param {string} props.cancelLabel
 */
export function LeaveApplicationsTable({
    applications,
    filters,
    labels,
    indexUrl,
    editUrl,
    destroyUrl,
    cancelLabel,
}) {
    const [search, setSearch] = useSyncedState(filters.search ?? '');
    const [leaveType, setLeaveType] = useSyncedState(filters.leave_type ?? '');
    const [staffType, setStaffType] = useSyncedState(filters.staff_type ?? '');
    const [removeId, setRemoveId] = useState(null);

    useEffect(() => {
        const handle = setTimeout(() => {
            router.get(
                indexUrl({
                    query: {
                        search: search.trim(),
                        leave_type: leaveType,
                        staff_type: staffType,
                        per_page: filters.per_page,
                        page: 1,
                    },
                }),
                {},
                { preserveState: true, preserveScroll: true, replace: true },
            );
        }, 350);

        return () => clearTimeout(handle);
    }, [search, leaveType, staffType, filters.per_page, indexUrl]);

    const rows = applications?.data ?? [];
    const currentPage = applications?.current_page ?? 1;
    const lastPage = applications?.last_page ?? 1;
    const total = applications?.total ?? 0;
    const perPage = applications?.per_page ?? 10;

    const summaryText = useMemo(() => {
        if (total === 0) {
            return labels.summaryEmpty;
        }

        return labels.paginationSummary
            .replace('{from}', String(applications?.from ?? 0))
            .replace('{to}', String(applications?.to ?? 0))
            .replace('{total}', String(total));
    }, [total, applications?.from, applications?.to, labels]);

    function leaveTypeLabel(type) {
        if (type === 'important') {
            return labels.leaveTypeImportant;
        }

        return labels.leaveTypeSick;
    }

    function goToPage(page) {
        router.get(
            indexUrl({ query: { ...filters, page } }),
            {},
            { preserveState: true, preserveScroll: true },
        );
    }

    function confirmRemove() {
        if (!removeId) {
            return;
        }

        router.delete(destroyUrl(removeId), {
            preserveScroll: true,
            onFinish: () => setRemoveId(null),
        });
    }

    return (
        <div className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <div className="space-y-2 lg:col-span-2">
                    <Label>{labels.searchLeavesPlaceholder}</Label>
                    <Input
                        type="search"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        placeholder={labels.searchLeavesPlaceholder}
                    />
                </div>
                <div className="space-y-2">
                    <Label>{labels.colLeaveType}</Label>
                    <Select
                        value={leaveType || 'all'}
                        onValueChange={(v) => setLeaveType(v === 'all' ? '' : v)}
                    >
                        <SelectTrigger>
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">{labels.leaveTypeAll}</SelectItem>
                            <SelectItem value="sick">{labels.leaveTypeSick}</SelectItem>
                            <SelectItem value="important">{labels.leaveTypeImportant}</SelectItem>
                        </SelectContent>
                    </Select>
                </div>
                <div className="space-y-2">
                    <Label>{labels.colStaffType}</Label>
                    <Select
                        value={staffType || 'all'}
                        onValueChange={(v) => setStaffType(v === 'all' ? '' : v)}
                    >
                        <SelectTrigger>
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">{labels.staffTypeAll}</SelectItem>
                            <SelectItem value="permanent">{labels.staffTypePermanent}</SelectItem>
                            <SelectItem value="temporary">{labels.staffTypeTemporary}</SelectItem>
                        </SelectContent>
                    </Select>
                </div>
            </div>

            <div className="overflow-x-auto rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-14">{labels.colSerial}</TableHead>
                            <TableHead>{labels.colStaff}</TableHead>
                            <TableHead>{labels.colLeaveType}</TableHead>
                            <TableHead>{labels.colFromDate}</TableHead>
                            <TableHead>{labels.colToDate}</TableHead>
                            <TableHead>{labels.colTotalDays}</TableHead>
                            <TableHead>{labels.colReason}</TableHead>
                            <TableHead className="w-24">{labels.colAction}</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {rows.length === 0 ? (
                            <TableRow>
                                <TableCell
                                    colSpan={8}
                                    className="text-muted-foreground h-24 text-center"
                                >
                                    {labels.emptyLeaves}
                                </TableCell>
                            </TableRow>
                        ) : (
                            rows.map((row, index) => (
                                <TableRow key={row.id}>
                                    <TableCell className="text-muted-foreground tabular-nums">
                                        {(currentPage - 1) * perPage + index + 1}
                                    </TableCell>
                                    <TableCell>
                                        <div className="font-medium">{row.staff_name}</div>
                                        <Badge variant="outline" className="mt-1">
                                            {row.staff_type === 'permanent'
                                                ? labels.staffTypePermanent
                                                : labels.staffTypeTemporary}
                                        </Badge>
                                    </TableCell>
                                    <TableCell>
                                        <Badge
                                            variant={
                                                row.leave_type === 'sick' ? 'secondary' : 'default'
                                            }
                                        >
                                            {leaveTypeLabel(row.leave_type)}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm tabular-nums">
                                        {formatEmployeeJoiningDateNumericOrDash(row.from_date)}
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm tabular-nums">
                                        {formatEmployeeJoiningDateNumericOrDash(row.to_date)}
                                    </TableCell>
                                    <TableCell className="tabular-nums">
                                        {row.total_days ?? '—'}
                                    </TableCell>
                                    <TableCell className="max-w-[12rem] truncate text-sm">
                                        {row.reason?.trim() ? row.reason : '—'}
                                    </TableCell>
                                    <TableCell>
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button
                                                    type="button"
                                                    variant="ghost"
                                                    size="icon"
                                                    aria-label={labels.actionsMenuAria}
                                                >
                                                    <MoreHorizontal className="size-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuItem asChild>
                                                    <Link href={editUrl(row.id)} prefetch>
                                                        <Pencil className="size-4" />
                                                        {labels.editLeave}
                                                    </Link>
                                                </DropdownMenuItem>
                                                <DropdownMenuItem
                                                    className="text-destructive focus:text-destructive"
                                                    onSelect={() => setRemoveId(row.id)}
                                                >
                                                    <Trash2 className="size-4" />
                                                    {labels.removeLeave}
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-2">
                <p className="text-muted-foreground text-sm">{summaryText}</p>
                <div className="flex gap-2">
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        disabled={currentPage <= 1}
                        onClick={() => goToPage(currentPage - 1)}
                    >
                        {labels.paginationPrevious}
                    </Button>
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        disabled={currentPage >= lastPage}
                        onClick={() => goToPage(currentPage + 1)}
                    >
                        {labels.paginationNext}
                    </Button>
                </div>
            </div>

            <ConfirmActionDialog
                open={removeId !== null}
                onOpenChange={(open) => !open && setRemoveId(null)}
                title={labels.confirmRemoveLeaveTitle}
                description={labels.confirmRemoveLeaveBody}
                confirmLabel={labels.removeLeave}
                cancelLabel={cancelLabel}
                onConfirm={confirmRemove}
            />
        </div>
    );
}
