import { Head, Link, router } from '@inertiajs/react';
import {
    AlertTriangle,
    Boxes,
    PackageCheck,
    PackageX,
    Scale,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import {
    EmptyState,
    PageHeader,
    SectionCard,
} from '@/components/crm/page-header';
import { KpiTile } from '@/components/crm/kpi-tile';
import {
    StockStatusBadge,
    VerificationBadge,
} from '@/components/crm/stock-badge';
import {
    DataPagination,
    FilterBar,
    FilterField,
    SearchInput,
    TableCard,
} from '@/components/crm/toolbar';
import { NativeSelect } from '@/components/crm/native-select';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { inventory } from '@/routes/warehouse';
import { show as productShow } from '@/routes/warehouse/products';
import type { InventoryRow, Paginated, WarehouseAbilities } from '@/types';

type Filters = {
    search: string | null;
    category: number | null;
    stock: string;
};

type Props = {
    rows: Paginated<InventoryRow>;
    filters: Filters;
    metrics: {
        outOfStock: number;
        lowStock: number;
        activeProducts: number;
        totalUnits: number;
        stockValue: number | null;
    };
    filterOptions: {
        categories: Array<{ value: number; label: string }>;
        stockStatuses: Array<{ value: string; label: string }>;
    };
    can: WarehouseAbilities;
};

export default function Inventory({
    rows,
    filters,
    metrics,
    filterOptions,
    can,
}: Props) {
    const [search, setSearch] = useState(filters.search ?? '');

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

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

        if (next.search) params.search = next.search;
        if (next.category) params.category = String(next.category);
        if (next.stock && next.stock !== 'attention') params.stock = next.stock;

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

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

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <Scale className="size-3.5 text-solar" />
                            <span>Warehouse</span>
                        </>
                    }
                    title="Stock levels"
                    description="What is on the shelf, what is already promised to a job, and what can still be picked. Available is derived from the other two; it is never typed in."
                    actions={
                        <Button variant="outline" size="sm" asChild>
                            <Link href={inventory().url}>Refresh</Link>
                        </Button>
                    }
                />

                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                    <KpiTile
                        label="Out of stock"
                        value={metrics.outOfStock}
                        hint="Nothing available to promise"
                        icon={PackageX}
                        tone={metrics.outOfStock > 0 ? 'danger' : 'success'}
                    />
                    <KpiTile
                        label="Low stock"
                        value={metrics.lowStock}
                        hint="At or below the reorder point"
                        icon={AlertTriangle}
                        tone={metrics.lowStock > 0 ? 'warning' : 'success'}
                    />
                    <KpiTile
                        label="Units on hand"
                        value={metrics.totalUnits.toLocaleString('en-AU')}
                        hint={`Across ${metrics.activeProducts} active products`}
                        icon={Boxes}
                        tone="solar"
                    />
                    {can.viewCosts ? (
                        <KpiTile
                            label="Stock value"
                            value={
                                metrics.stockValue === null
                                    ? '—'
                                    : `$${metrics.stockValue.toLocaleString(
                                          'en-AU',
                                          {
                                              minimumFractionDigits: 0,
                                              maximumFractionDigits: 0,
                                          },
                                      )}`
                            }
                            hint="At purchase cost, GST as recorded"
                            icon={Scale}
                            tone="emerald"
                        />
                    ) : (
                        <KpiTile
                            label="Active products"
                            value={metrics.activeProducts}
                            hint="In the catalogue"
                            icon={PackageCheck}
                            tone="info"
                        />
                    )}
                </div>

                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        apply({ search });
                    }}
                >
                    <FilterBar>
                        <SearchInput
                            value={search}
                            onChange={setSearch}
                            placeholder="Code, name or location"
                            className="min-w-[16rem]"
                        />
                        <FilterField label="Category" className="w-52">
                            <NativeSelect
                                value={
                                    filters.category
                                        ? String(filters.category)
                                        : ''
                                }
                                onChange={(event) =>
                                    apply({
                                        category: event.target.value
                                            ? Number(event.target.value)
                                            : null,
                                    })
                                }
                            >
                                <option value="">All categories</option>
                                {filterOptions.categories.map((category) => (
                                    <option
                                        key={category.value}
                                        value={String(category.value)}
                                    >
                                        {category.label}
                                    </option>
                                ))}
                            </NativeSelect>
                        </FilterField>
                        <FilterField label="Show" className="w-44">
                            <NativeSelect
                                value={filters.stock}
                                onChange={(event) =>
                                    apply({ stock: event.target.value })
                                }
                            >
                                {filterOptions.stockStatuses.map((status) => (
                                    <option
                                        key={status.value}
                                        value={status.value}
                                    >
                                        {status.label}
                                    </option>
                                ))}
                            </NativeSelect>
                        </FilterField>
                    </FilterBar>
                </form>

                {rows.data.length === 0 ? (
                    <SectionCard title="Stock" flush>
                        <EmptyState
                            icon={PackageCheck}
                            title="Nothing needs restocking"
                            description="Every active product is above its reorder point, or has no minimum set."
                        />
                    </SectionCard>
                ) : (
                    <TableCard>
                        <Table>
                            <TableHeader>
                                <TableRow className="hover:bg-transparent">
                                    <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">
                                        Provenance
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        On hand
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Reserved
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Damaged
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Available
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Minimum
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Suggested order
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Status
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {rows.data.map((row) => (
                                    <TableRow key={row.id}>
                                        <TableCell>
                                            <Link
                                                href={productShow(row.id).url}
                                                className="group/cell block"
                                            >
                                                <span className="block text-sm font-medium group-hover/cell:underline">
                                                    {row.name}
                                                </span>
                                                <span className="block font-mono text-xs text-muted-foreground">
                                                    {row.sku}
                                                    {row.storage_location
                                                        ? ` · ${row.storage_location}`
                                                        : ''}
                                                </span>
                                            </Link>
                                        </TableCell>
                                        <TableCell>
                                            <VerificationBadge
                                                verification={row.verification}
                                            />
                                        </TableCell>
                                        <TableCell className="text-right tabular-nums crm-num">
                                            {row.physical_quantity}
                                        </TableCell>
                                        <TableCell className="text-right text-muted-foreground tabular-nums crm-num">
                                            {row.reserved_quantity}
                                        </TableCell>
                                        <TableCell className="text-right text-muted-foreground tabular-nums crm-num">
                                            {row.damaged_quantity}
                                        </TableCell>
                                        <TableCell className="text-right font-medium tabular-nums crm-num">
                                            {row.available_quantity}
                                        </TableCell>
                                        <TableCell className="text-right text-muted-foreground tabular-nums crm-num">
                                            {row.minimum_stock}
                                        </TableCell>
                                        <TableCell className="text-right tabular-nums crm-num">
                                            {row.suggested_order_quantity > 0
                                                ? row.suggested_order_quantity
                                                : '—'}
                                        </TableCell>
                                        <TableCell>
                                            <StockStatusBadge
                                                status={row.stock_status}
                                            />
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                        <DataPagination page={rows} noun="products" />
                    </TableCard>
                )}
            </div>
        </>
    );
}
