import { router } from '@inertiajs/react';
import { useEffect, useMemo } from 'react';
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 { useLanguage } from '@/contexts/language-context';
import { useSyncedState } from '@/hooks/use-synced-state';

/**
 * @param {object} props
 * @param {import('@inertiajs/core').Paginator<any>} props.sessions
 * @param {{ search: string, per_page: number }} props.filters
 * @param {Record<string, string>} props.labels
 * @param {(opts?: { query?: Record<string, string | number> }) => string} props.indexUrl
 */
export function LoginHistoriesTable({ sessions, filters, labels, indexUrl }) {
    const { formatDateTime } = useLanguage();
    const [search, setSearch] = useSyncedState(filters.search ?? '');

    useEffect(() => {
        const handle = setTimeout(() => {
            const next = search.trim();
            const current = (filters.search ?? '').trim();
            if (next === current) {
                return;
            }
            router.get(
                indexUrl({
                    query: {
                        search: next,
                        per_page: filters.per_page,
                        page: 1,
                    },
                }),
                {},
                { preserveState: true, preserveScroll: true, replace: true },
            );
        }, 350);

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

    const rows = sessions?.data ?? [];
    const currentPage = sessions?.current_page ?? 1;
    const lastPage = sessions?.last_page ?? 1;
    const from = sessions?.from;
    const to = sessions?.to;
    const total = sessions?.total ?? 0;

    const summaryText = useMemo(() => {
        if (total === 0) {
            return labels.summaryEmpty;
        }
        return labels.paginationSummary
            .replace('{from}', String(from ?? 0))
            .replace('{to}', String(to ?? 0))
            .replace('{total}', String(total));
    }, [from, to, total, labels.paginationSummary, labels.summaryEmpty]);

    const pagePositionText = useMemo(
        () =>
            labels.paginationPages
                .replace('{page}', String(currentPage))
                .replace('{pages}', String(lastPage)),
        [currentPage, lastPage, labels.paginationPages],
    );

    const goToPage = (page) => {
        router.get(
            indexUrl({
                query: {
                    search: filters.search,
                    per_page: filters.per_page,
                    page,
                },
            }),
            {},
            { preserveState: true, preserveScroll: true },
        );
    };

    const updatePerPage = (perPage) => {
        router.get(
            indexUrl({
                query: {
                    search: filters.search,
                    per_page: perPage,
                    page: 1,
                },
            }),
            {},
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    const formatDuration = (seconds) => {
        if (seconds == null || seconds < 0) {
            return '—';
        }
        if (seconds < 60) {
            return '< 1m';
        }
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        if (hours > 0 && minutes > 0) {
            return `${hours}h ${minutes}m`;
        }
        if (hours > 0) {
            return `${hours}h`;
        }
        return `${minutes}m`;
    };

    return (
        <div className="space-y-4">
            <div className="max-w-md space-y-2">
                <Label htmlFor="login-history-search">{labels.searchLabel}</Label>
                <Input
                    id="login-history-search"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder={labels.searchPlaceholder}
                />
            </div>

            <div className="overflow-x-auto rounded-lg border border-border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-14">{labels.colSerial}</TableHead>
                            <TableHead>{labels.colUser}</TableHead>
                            <TableHead>{labels.colEmail}</TableHead>
                            <TableHead>{labels.colLoggedInAt}</TableHead>
                            <TableHead>{labels.colSessionDuration}</TableHead>
                            <TableHead>{labels.colLastActivity}</TableHead>
                            <TableHead>{labels.colIp}</TableHead>
                            <TableHead>{labels.colUserAgent}</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {rows.length === 0 ? (
                            <TableRow>
                                <TableCell
                                    colSpan={8}
                                    className="text-muted-foreground h-24 text-center"
                                >
                                    {labels.empty}
                                </TableCell>
                            </TableRow>
                        ) : (
                            rows.map((row, index) => (
                                <TableRow key={row.id}>
                                    <TableCell className="text-muted-foreground">
                                        {(from ?? 0) + index}
                                    </TableCell>
                                    <TableCell className="font-medium">{row.user_name}</TableCell>
                                    <TableCell className="text-muted-foreground">
                                        {row.user_email}
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm">
                                        {formatDateTime(row.logged_in_at)}
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm tabular-nums">
                                        {formatDuration(row.session_duration_seconds)}
                                    </TableCell>
                                    <TableCell className="whitespace-nowrap text-sm">
                                        {formatDateTime(row.last_activity)}
                                    </TableCell>
                                    <TableCell className="text-muted-foreground text-xs">
                                        {row.ip_address ?? '—'}
                                    </TableCell>
                                    <TableCell
                                        className="text-muted-foreground max-w-xs truncate text-xs"
                                        title={row.user_agent ?? undefined}
                                    >
                                        {row.user_agent ?? '—'}
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <p className="text-muted-foreground text-sm">{summaryText}</p>
                <div className="flex flex-wrap items-center gap-3">
                    <div className="flex items-center gap-2">
                        <Label htmlFor="login-per-page" className="text-sm whitespace-nowrap">
                            {labels.rowsPerPage}
                        </Label>
                        <Select
                            value={String(filters.per_page)}
                            onValueChange={(value) => updatePerPage(Number(value))}
                        >
                            <SelectTrigger id="login-per-page" className="w-20">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                {[10, 25, 50].map((n) => (
                                    <SelectItem key={n} value={String(n)}>
                                        {n}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    <span className="text-muted-foreground text-sm">{pagePositionText}</span>
                    <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>
        </div>
    );
}
