import { Head, Link, router } from '@inertiajs/react';
import { ClipboardList, SearchX } from 'lucide-react';
import { useEffect, useState } from 'react';
import { EmptyState, PageHeader } from '@/components/crm/page-header';
import {
    FilterBar,
    FilterField,
    SearchInput,
    TableCard,
} from '@/components/crm/toolbar';
import { NativeSelect } from '@/components/crm/native-select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { DataPagination } from '@/components/crm/toolbar';
import { cn } from '@/lib/utils';
import { index as movementsIndex } from '@/routes/warehouse/movements';
import { show as productShow } from '@/routes/warehouse/products';
import type { Option, Paginated, StockMovementRow } from '@/types';

type Filters = {
    search: string | null;
    type: string | null;
    from: string | null;
    to: string | null;
};

export default function Movements({
    movements,
    filters,
    filterOptions,
    totals,
}: {
    movements: Paginated<StockMovementRow>;
    filters: Filters;
    filterOptions: { types: Option[] };
    totals: { today: number; thisWeek: number };
}) {
    const [search, setSearch] = useState(filters.search ?? '');
    const [from, setFrom] = useState(filters.from ?? '');
    const [to, setTo] = useState(filters.to ?? '');

    useEffect(() => {
        setSearch(filters.search ?? '');
        setFrom(filters.from ?? '');
        setTo(filters.to ?? '');
    }, [filters.search, filters.from, filters.to]);

    const apply = (patch: Partial<Filters>) => {
        const next = { ...filters, ...patch };
        const params: Record<string, string> = {};

        if (next.search) params.search = next.search;
        if (next.type) params.type = next.type;
        if (next.from) params.from = next.from;
        if (next.to) params.to = next.to;

        router.get(movementsIndex().url, params, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    const hasFilters = Boolean(
        filters.search || filters.type || filters.from || filters.to,
    );

    return (
        <>
            <Head title="Stock ledger" />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <ClipboardList className="size-3.5 text-solar" />
                            <span>Warehouse</span>
                        </>
                    }
                    title="Stock ledger"
                    description="Every change to a quantity, newest first: who moved it, when, how many, and why. Rows are never edited, so the shelf count can always be explained."
                    actions={
                        <div className="flex gap-4 text-xs text-muted-foreground">
                            <span>
                                <span className="font-medium text-foreground crm-num">
                                    {totals.today}
                                </span>{' '}
                                today
                            </span>
                            <span>
                                <span className="font-medium text-foreground crm-num">
                                    {totals.thisWeek}
                                </span>{' '}
                                this week
                            </span>
                        </div>
                    }
                />

                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        apply({ search, from, to });
                    }}
                >
                    <FilterBar
                        actions={
                            hasFilters ? (
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="sm"
                                    onClick={() =>
                                        router.get(
                                            movementsIndex().url,
                                            {},
                                            {
                                                preserveState: true,
                                                replace: true,
                                            },
                                        )
                                    }
                                >
                                    Clear
                                </Button>
                            ) : undefined
                        }
                    >
                        <SearchInput
                            value={search}
                            onChange={setSearch}
                            placeholder="Product code, name or brand"
                            className="min-w-[15rem]"
                        />
                        <FilterField label="Movement" className="w-48">
                            <NativeSelect
                                value={filters.type ?? ''}
                                onChange={(event) =>
                                    apply({
                                        type: event.target.value || null,
                                    })
                                }
                            >
                                <option value="">All movements</option>
                                {filterOptions.types.map((type) => (
                                    <option key={type.value} value={type.value}>
                                        {type.label}
                                    </option>
                                ))}
                            </NativeSelect>
                        </FilterField>
                        <FilterField label="From" className="w-40">
                            <Input
                                type="date"
                                value={from}
                                onChange={(event) =>
                                    apply({ from: event.target.value || null })
                                }
                            />
                        </FilterField>
                        <FilterField label="To" className="w-40">
                            <Input
                                type="date"
                                value={to}
                                onChange={(event) =>
                                    apply({ to: event.target.value || null })
                                }
                            />
                        </FilterField>
                    </FilterBar>
                </form>

                {movements.data.length === 0 ? (
                    <TableCard>
                        <EmptyState
                            icon={hasFilters ? SearchX : ClipboardList}
                            title={
                                hasFilters
                                    ? 'No movements match'
                                    : 'Nothing has moved yet'
                            }
                            description={
                                hasFilters
                                    ? 'Try a wider date range or a different movement type.'
                                    : 'Recording a receipt, issue or correction on a product page writes the first line here.'
                            }
                        />
                    </TableCard>
                ) : (
                    <TableCard>
                        <Table>
                            <TableHeader>
                                <TableRow className="hover:bg-transparent">
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        When
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Product
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Movement
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Change
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Balance
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Detail
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        By
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {movements.data.map((movement) => (
                                    <TableRow key={movement.id}>
                                        <TableCell className="text-xs whitespace-nowrap text-muted-foreground">
                                            {movement.occurred_at}
                                        </TableCell>
                                        <TableCell>
                                            {movement.product ? (
                                                <Link
                                                    href={
                                                        productShow(
                                                            movement.product.id,
                                                        ).url
                                                    }
                                                    className="group/cell block"
                                                >
                                                    <span className="block text-sm font-medium group-hover/cell:underline">
                                                        {movement.product.name}
                                                    </span>
                                                    <span className="block font-mono text-xs text-muted-foreground">
                                                        {movement.product.sku}
                                                    </span>
                                                </Link>
                                            ) : (
                                                '—'
                                            )}
                                        </TableCell>
                                        <TableCell className="text-sm">
                                            {movement.type.label}
                                        </TableCell>
                                        <TableCell
                                            className={cn(
                                                'text-right font-medium tabular-nums crm-num',
                                                movement.quantity > 0 &&
                                                    'text-success',
                                                movement.quantity < 0 &&
                                                    'text-danger',
                                            )}
                                        >
                                            {movement.quantity > 0 ? '+' : ''}
                                            {movement.quantity}
                                        </TableCell>
                                        <TableCell className="text-right tabular-nums crm-num">
                                            {movement.balance_after}
                                        </TableCell>
                                        <TableCell className="max-w-[18rem] text-xs text-muted-foreground">
                                            {movement.reason ??
                                                movement.reference ??
                                                (movement.job
                                                    ? `Job ${movement.job.job_number}`
                                                    : '—')}
                                        </TableCell>
                                        <TableCell className="text-xs whitespace-nowrap text-muted-foreground">
                                            {movement.user ?? 'System'}
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                        <DataPagination page={movements} noun="movements" />
                    </TableCard>
                )}
            </div>
        </>
    );
}
