import { router } from '@inertiajs/react';
import { useEffect, useMemo } from 'react';
import { AppDateInput } from '@/components/ui/app-date-input';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
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 {
    formatAppDateTimeOrDash,
    formatEmployeeJoiningDateNumericOrDash,
} from '@/lib/dates';

/**
 * @param {string} status
 * @param {Record<string, string>} labels
 */
function dayStatusLabel(status, labels) {
    switch (status) {
        case 'active':
            return labels.statusActive;
        case 'absent':
            return labels.statusAbsent;
        case 'sick_leave':
            return labels.statusSickLeave;
        case 'important_leave':
            return labels.statusImportantLeave;
        default:
            return status;
    }
}

/**
 * @param {string} status
 */
function dayStatusVariant(status) {
    switch (status) {
        case 'active':
            return 'default';
        case 'absent':
            return 'destructive';
        case 'sick_leave':
            return 'secondary';
        case 'important_leave':
            return 'outline';
        default:
            return 'outline';
    }
}

/**
 * @param {object} props
 * @param {import('@inertiajs/core').Paginator<any>} props.records
 * @param {object} props.filters
 * @param {string[]} [props.dayStatuses]
 * @param {Record<string, string>} props.labels
 * @param {(opts?: object) => string} props.indexUrl
 */
export function AttendanceRecordsTable({ records, filters, dayStatuses, labels, indexUrl }) {
    const [staffId, setStaffId] = useSyncedState(filters.staff_id ?? '');
    const [staffType, setStaffType] = useSyncedState(filters.staff_type ?? '');
    const [dayStatus, setDayStatus] = useSyncedState(filters.day_status ?? '');
    const [dateFrom, setDateFrom] = useSyncedState(filters.date_from ?? '');
    const [dateTo, setDateTo] = useSyncedState(filters.date_to ?? '');

    useEffect(() => {
        const handle = setTimeout(() => {
            router.get(
                indexUrl({
                    query: {
                        staff_id: staffId.trim(),
                        staff_type: staffType,
                        day_status: dayStatus,
                        date_from: dateFrom,
                        date_to: dateTo,
                        ...(filters.salary_month
                            ? { salary_month: filters.salary_month }
                            : {}),
                        per_page: filters.per_page,
                        page: 1,
                    },
                }),
                {},
                { preserveState: true, preserveScroll: true, replace: true },
            );
        }, 350);

        return () => clearTimeout(handle);
    }, [staffId, staffType, dayStatus, dateFrom, dateTo, filters.per_page, indexUrl]);

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

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

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

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

    return (
        <div className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                <div className="space-y-2">
                    <Label htmlFor="attendance-date-from">{labels.dateFrom}</Label>
                    <AppDateInput
                        id="attendance-date-from"
                        forceJalali
                        value={dateFrom}
                        onChange={setDateFrom}
                    />
                </div>
                <div className="space-y-2">
                    <Label htmlFor="attendance-date-to">{labels.dateTo}</Label>
                    <AppDateInput
                        id="attendance-date-to"
                        forceJalali
                        value={dateTo}
                        onChange={setDateTo}
                    />
                </div>
                <div className="space-y-2">
                    <Label>{labels.colDayStatus}</Label>
                    <Select
                        value={dayStatus || 'all'}
                        onValueChange={(v) => setDayStatus(v === 'all' ? '' : v)}
                    >
                        <SelectTrigger>
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">{labels.dayStatusAll}</SelectItem>
                            {(dayStatuses ?? ['active', 'absent', 'sick_leave', 'important_leave']).map(
                                (status) => (
                                    <SelectItem key={status} value={status}>
                                        {dayStatusLabel(status, labels)}
                                    </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 className="space-y-2">
                    <Label htmlFor="attendance-staff-id">{labels.searchStaffId}</Label>
                    <Input
                        id="attendance-staff-id"
                        type="number"
                        min={1}
                        inputMode="numeric"
                        value={staffId}
                        onChange={(e) => setStaffId(e.target.value)}
                        placeholder={labels.searchStaffIdPlaceholder}
                    />
                </div>
            </div>

            <div className="overflow-x-auto rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-14">{labels.colSerial}</TableHead>
                            <TableHead>{labels.colWorkDate}</TableHead>
                            <TableHead>{labels.colStaffId}</TableHead>
                            <TableHead>{labels.colStaff}</TableHead>
                            <TableHead>{labels.colStaffType}</TableHead>
                            <TableHead>{labels.colDayStatus}</TableHead>
                            <TableHead>{labels.colCheckIn}</TableHead>
                            <TableHead>{labels.colCheckOut}</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {rows.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={8} className="text-muted-foreground h-24 text-center">
                                    {labels.emptyRecords}
                                </TableCell>
                            </TableRow>
                        ) : (
                            rows.map((row, index) => (
                                <TableRow key={row.id}>
                                    <TableCell className="text-muted-foreground tabular-nums">
                                        {(currentPage - 1) * perPage + index + 1}
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm tabular-nums">
                                        {formatEmployeeJoiningDateNumericOrDash(row.work_date)}
                                    </TableCell>
                                    <TableCell className="tabular-nums">{row.staff_id}</TableCell>
                                    <TableCell className="font-medium">{row.staff_name}</TableCell>
                                    <TableCell>
                                        <Badge variant="outline">
                                            {row.staff_type === 'permanent'
                                                ? labels.staffTypePermanent
                                                : labels.staffTypeTemporary}
                                        </Badge>
                                    </TableCell>
                                    <TableCell>
                                        <Badge variant={dayStatusVariant(row.day_status)}>
                                            {dayStatusLabel(row.day_status, labels)}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm tabular-nums">
                                        {row.day_status === 'active' ||
                                        row.day_status === 'absent' ? (
                                            formatAppDateTimeOrDash(row.check_in_at, 'fa')
                                        ) : (
                                            '—'
                                        )}
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm tabular-nums">
                                        {row.day_status === 'active' ||
                                        row.day_status === 'absent' ? (
                                            formatAppDateTimeOrDash(row.check_out_at, 'fa')
                                        ) : (
                                            '—'
                                        )}
                                    </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>
        </div>
    );
}
