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 {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useSyncedState } from '@/hooks/use-synced-state';
import { formatQuantityOrDash } from '@/lib/dates';
import { cn } from '@/lib/utils';

/**
 * @param {object} props
 * @param {import('@inertiajs/core').Paginator<any>} props.stocks
 * @param {{ search: string, per_page: number }} props.filters
 * @param {Record<string, string>} props.labels
 * @param {'en'|'fa'} props.locale
 * @param {(opts?: { query?: Record<string, string | number> }) => string} props.indexUrl
 */
export function FinishedGoodsStocksTable({ stocks, filters, labels, locale, indexUrl }) {
    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.search, filters.per_page, indexUrl]);

    const rows = stocks?.data ?? [];
    const currentPage = stocks?.current_page ?? 1;
    const lastPage = stocks?.last_page ?? 1;
    const from = stocks?.from;
    const to = stocks?.to;
    const total = stocks?.total ?? 0;

    const summaryText = useMemo(() => {
        if (total === 0) {
            return labels.empty;
        }
        return labels.paginationSummary
            .replace('{from}', String(from ?? 0))
            .replace('{to}', String(to ?? 0))
            .replace('{total}', String(total));
    }, [from, to, total, labels.empty, labels.paginationSummary]);

    const pagePositionText = useMemo(
        () =>
            labels.paginationPages
                .replace('{page}', String(currentPage))
                .replace('{pages}', String(Math.max(lastPage, 1))),
        [currentPage, lastPage, labels.paginationPages],
    );

    function goToPage(page) {
        if (page < 1 || page > lastPage) {
            return;
        }
        router.get(
            indexUrl({
                query: {
                    search: filters.search ?? '',
                    per_page: filters.per_page,
                    page,
                },
            }),
            {},
            { preserveState: true, preserveScroll: true },
        );
    }

    function setPerPage(next) {
        router.get(
            indexUrl({
                query: {
                    search: filters.search ?? '',
                    per_page: next,
                    page: 1,
                },
            }),
            {},
            { preserveState: true, preserveScroll: true },
        );
    }

    return (
        <div className="space-y-4">
            <div className="flex max-w-sm flex-col gap-2">
                <Input
                    type="search"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder={labels.searchPlaceholder}
                    className="h-9"
                />
            </div>

            <Table>
                <TableHeader>
                    <TableRow>
                        <TableHead className="w-16">{labels.colSerial}</TableHead>
                        <TableHead>{labels.colName}</TableHead>
                        <TableHead>{labels.colUnit}</TableHead>
                        <TableHead>{labels.colStock}</TableHead>
                        <TableHead>{labels.colDefectiveStock}</TableHead>
                        <TableHead>{labels.colExpiredStock}</TableHead>
                        <TableHead>{labels.colInProduction}</TableHead>
                        <TableHead>{labels.colStatus}</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) => {
                            const stock = Number(row.stock_on_hand ?? 0);
                            const defectiveStock = Number(row.defective_stock ?? 0);
                            const expiredStock = Number(row.expired_stock ?? 0);
                            const inProduction = Number(row.in_production ?? 0);

                            return (
                                <TableRow key={row.id}>
                                    <TableCell className="text-muted-foreground tabular-nums">
                                        {from != null ? from + index : index + 1}
                                    </TableCell>
                                    <TableCell className="font-medium">{row.name}</TableCell>
                                    <TableCell>{row.unit_name || '—'}</TableCell>
                                    <TableCell
                                        className={cn(
                                            'tabular-nums font-semibold',
                                            stock > 0
                                                ? 'text-emerald-700 dark:text-emerald-400'
                                                : 'text-muted-foreground',
                                        )}
                                    >
                                        {formatQuantityOrDash(row.stock_on_hand, locale)}
                                        {row.unit_name ? (
                                            <span className="text-muted-foreground ms-1 text-xs font-normal">
                                                {row.unit_name}
                                            </span>
                                        ) : null}
                                    </TableCell>
                                    <TableCell
                                        className={cn(
                                            'tabular-nums',
                                            defectiveStock > 0
                                                ? 'font-medium text-amber-700 dark:text-amber-400'
                                                : 'text-muted-foreground',
                                        )}
                                    >
                                        {formatQuantityOrDash(row.defective_stock, locale)}
                                    </TableCell>
                                    <TableCell
                                        className={cn(
                                            'tabular-nums',
                                            expiredStock > 0
                                                ? 'font-medium text-rose-700 dark:text-rose-400'
                                                : 'text-muted-foreground',
                                        )}
                                    >
                                        {formatQuantityOrDash(row.expired_stock, locale)}
                                    </TableCell>
                                    <TableCell
                                        className={cn(
                                            'tabular-nums',
                                            inProduction > 0
                                                ? 'font-medium'
                                                : 'text-muted-foreground',
                                        )}
                                    >
                                        {formatQuantityOrDash(row.in_production, locale)}
                                        {row.unit_name && inProduction > 0 ? (
                                            <span className="text-muted-foreground ms-1 text-xs font-normal">
                                                {row.unit_name}
                                            </span>
                                        ) : null}
                                    </TableCell>
                                    <TableCell>
                                        <span
                                            className={cn(
                                                'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                                                row.is_active
                                                    ? 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-400'
                                                    : 'bg-muted text-muted-foreground',
                                            )}
                                        >
                                            {row.is_active
                                                ? labels.statusActive
                                                : labels.statusInactive}
                                        </span>
                                    </TableCell>
                                </TableRow>
                            );
                        })
                    )}
                </TableBody>
            </Table>

            {total > 0 ? (
                <div className="flex flex-col gap-4 border-t border-border pt-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex flex-wrap items-center gap-2">
                        <Label
                            htmlFor="finished-goods-stocks-page-size"
                            className="text-muted-foreground whitespace-nowrap text-sm"
                        >
                            {labels.rowsPerPage}
                        </Label>
                        <select
                            id="finished-goods-stocks-page-size"
                            className="border-input bg-background h-9 rounded-md border px-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
                            value={filters.per_page}
                            onChange={(e) => setPerPage(Number(e.target.value))}
                        >
                            {[5, 10, 25, 50].map((n) => (
                                <option key={n} value={n}>
                                    {n}
                                </option>
                            ))}
                        </select>
                        <span className="text-muted-foreground text-sm tabular-nums">
                            {summaryText}
                        </span>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => goToPage(currentPage - 1)}
                            disabled={currentPage <= 1}
                        >
                            {labels.paginationPrevious}
                        </Button>
                        <span className="text-muted-foreground min-w-[8rem] text-center text-sm tabular-nums">
                            {pagePositionText}
                        </span>
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => goToPage(currentPage + 1)}
                            disabled={currentPage >= lastPage}
                        >
                            {labels.paginationNext}
                        </Button>
                    </div>
                </div>
            ) : null}
        </div>
    );
}
