import { Head, Link } from '@inertiajs/react';
import {
    AlertTriangle,
    Boxes,
    ClipboardList,
    Info,
    PackageCheck,
    PackageX,
    Tags,
    Truck,
    Warehouse,
} from 'lucide-react';
import {
    Callout,
    EmptyState,
    PageHeader,
    SectionCard,
} from '@/components/crm/page-header';
import { KpiTile } from '@/components/crm/kpi-tile';
import { StockStatusBadge } from '@/components/crm/stock-badge';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { cn } from '@/lib/utils';
import { inventory } from '@/routes/warehouse';
import { index as movementsIndex } from '@/routes/warehouse/movements';
import {
    index as productsIndex,
    show as productShow,
} from '@/routes/warehouse/products';
import { index as categoriesIndex } from '@/routes/warehouse/categories';
import { index as suppliersIndex } from '@/routes/warehouse/suppliers';
import type {
    ProductSummary,
    StockMovementRow,
    WarehouseAbilities,
} from '@/types';

type Props = {
    metrics: {
        activeProducts: number;
        lowStock: number;
        outOfStock: number;
        categories: number;
        suppliers: number;
        stockValue: number | null;
        movementsThisWeek: number;
    };
    lowStock: ProductSummary[];
    recentMovements: StockMovementRow[];
    byCategory: Array<{
        id: number;
        name: string;
        code: string | null;
        products_count: number;
    }>;
    can: WarehouseAbilities;
};

export default function WarehouseDashboard({
    metrics,
    lowStock,
    recentMovements,
    byCategory,
    can,
}: Props) {
    const largestCategory = Math.max(
        1,
        ...byCategory.map((category) => category.products_count),
    );

    return (
        <>
            <Head title="Warehouse" />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <Warehouse className="size-3.5 text-solar" />
                            <span>Warehouse</span>
                        </>
                    }
                    title="Warehouse"
                    description="The catalogue the company buys from, the stock it holds, and the ledger that explains every change."
                    actions={
                        <>
                            <Button variant="outline" size="sm" asChild>
                                <Link href={movementsIndex().url}>
                                    <ClipboardList className="size-4" />
                                    Stock ledger
                                </Link>
                            </Button>
                            <Button size="sm" asChild>
                                <Link href={productsIndex().url}>
                                    <Boxes className="size-4" />
                                    Product catalogue
                                </Link>
                            </Button>
                        </>
                    }
                />

                {recentMovements.length === 0 && metrics.activeProducts > 0 ? (
                    <Callout
                        tone="info"
                        icon={Info}
                        title="A starter catalogue, with no stock recorded yet"
                    >
                        These products are headings to fill in: no brand, model
                        or quantity has been claimed. Open a product and record
                        a receipt when the company's first delivery arrives, and
                        the ledger starts from there.
                    </Callout>
                ) : null}

                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                    <KpiTile
                        label="Catalogue"
                        value={metrics.activeProducts}
                        hint={`${metrics.categories} categories`}
                        icon={Boxes}
                        tone="solar"
                        href={productsIndex().url}
                    />
                    <KpiTile
                        label="Low stock"
                        value={metrics.lowStock}
                        hint="At or below the reorder point"
                        icon={AlertTriangle}
                        tone={metrics.lowStock > 0 ? 'warning' : 'success'}
                        href={`${inventory().url}?stock=low`}
                    />
                    <KpiTile
                        label="Out of stock"
                        value={metrics.outOfStock}
                        hint="Nothing available to promise"
                        icon={PackageX}
                        tone={metrics.outOfStock > 0 ? 'danger' : 'success'}
                        href={`${inventory().url}?stock=out`}
                    />
                    {can.viewCosts ? (
                        <KpiTile
                            label="Stock value"
                            value={
                                metrics.stockValue === null
                                    ? '—'
                                    : `$${metrics.stockValue.toLocaleString(
                                          'en-AU',
                                          {
                                              minimumFractionDigits: 0,
                                              maximumFractionDigits: 0,
                                          },
                                      )}`
                            }
                            hint="On-hand quantity at purchase cost"
                            icon={Tags}
                            tone="emerald"
                        />
                    ) : (
                        <KpiTile
                            label="Movements"
                            value={metrics.movementsThisWeek}
                            hint="Recorded this week"
                            icon={ClipboardList}
                            tone="info"
                            href={movementsIndex().url}
                        />
                    )}
                </div>

                <div className="grid gap-5 lg:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]">
                    <SectionCard
                        title="Needs attention"
                        description="Products with nothing available, or sitting at their reorder point."
                        icon={AlertTriangle}
                        tone={
                            metrics.lowStock + metrics.outOfStock > 0
                                ? 'warning'
                                : 'success'
                        }
                        flush
                        actions={
                            <Button variant="outline" size="sm" asChild>
                                <Link href={inventory().url}>
                                    All stock levels
                                </Link>
                            </Button>
                        }
                    >
                        {lowStock.length === 0 && metrics.outOfStock === 0 ? (
                            <EmptyState
                                icon={PackageCheck}
                                title="Nothing is running out"
                                description="Every active product has stock above its reorder point."
                            />
                        ) : lowStock.length === 0 ? (
                            <EmptyState
                                icon={PackageX}
                                title={`${metrics.outOfStock} products have nothing available`}
                                description="They are either not stocked yet or have been fully issued. Open the stock levels to review them."
                            />
                        ) : (
                            <div className="crm-scroll overflow-x-auto">
                                <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-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-[11px] font-semibold tracking-wide uppercase">
                                                Status
                                            </TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {lowStock.map((product) => (
                                            <TableRow key={product.id}>
                                                <TableCell>
                                                    <Link
                                                        href={
                                                            productShow(
                                                                product.id,
                                                            ).url
                                                        }
                                                        className="group/cell block"
                                                    >
                                                        <span className="block text-sm font-medium group-hover/cell:underline">
                                                            {product.name}
                                                        </span>
                                                        <span className="block font-mono text-xs text-muted-foreground">
                                                            {product.sku}
                                                        </span>
                                                    </Link>
                                                </TableCell>
                                                <TableCell className="text-right font-medium tabular-nums crm-num">
                                                    {product.available_quantity}
                                                </TableCell>
                                                <TableCell className="text-right text-muted-foreground tabular-nums crm-num">
                                                    {product.minimum_stock}
                                                </TableCell>
                                                <TableCell>
                                                    <StockStatusBadge
                                                        status={
                                                            product.stock_status
                                                        }
                                                    />
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>
                        )}
                    </SectionCard>

                    <div className="flex flex-col gap-5">
                        <SectionCard
                            title="The catalogue"
                            description="Where the products sit today."
                            icon={Boxes}
                        >
                            {byCategory.length === 0 ? (
                                <p className="text-xs text-muted-foreground">
                                    No products have a category yet.
                                </p>
                            ) : (
                                <ul className="flex flex-col gap-2.5">
                                    {byCategory.slice(0, 8).map((category) => (
                                        <li key={category.id}>
                                            <div className="flex items-baseline justify-between gap-3 text-sm">
                                                <span className="truncate">
                                                    {category.name}
                                                </span>
                                                <span className="text-xs text-muted-foreground crm-num">
                                                    {category.products_count}
                                                </span>
                                            </div>
                                            <div className="mt-1 h-1 overflow-hidden rounded-full bg-muted">
                                                <div
                                                    className="h-full rounded-full bg-solar/70"
                                                    style={{
                                                        width: `${Math.max(
                                                            6,
                                                            (category.products_count /
                                                                largestCategory) *
                                                                100,
                                                        )}%`,
                                                    }}
                                                />
                                            </div>
                                        </li>
                                    ))}
                                </ul>
                            )}
                            <div className="mt-4 flex flex-wrap gap-2">
                                <Button variant="outline" size="sm" asChild>
                                    <Link href={categoriesIndex().url}>
                                        Categories
                                    </Link>
                                </Button>
                                <Button variant="outline" size="sm" asChild>
                                    <Link href={suppliersIndex().url}>
                                        <Truck className="size-4" />
                                        Suppliers ({metrics.suppliers})
                                    </Link>
                                </Button>
                            </div>
                        </SectionCard>

                        <SectionCard
                            title="Recent movements"
                            description="What left, arrived or was promised."
                            icon={ClipboardList}
                        >
                            {recentMovements.length === 0 ? (
                                <p className="text-xs leading-relaxed text-muted-foreground">
                                    Nothing has moved yet. Receiving stock from
                                    a product page writes the first line.
                                </p>
                            ) : (
                                <ul className="flex flex-col gap-3">
                                    {recentMovements
                                        .slice(0, 8)
                                        .map((movement) => (
                                            <li
                                                key={movement.id}
                                                className="flex items-start justify-between gap-3 border-b border-hairline pb-3 last:border-0 last:pb-0"
                                            >
                                                <div className="min-w-0">
                                                    <p className="truncate text-sm">
                                                        {movement.product
                                                            ?.name ?? 'Product'}
                                                    </p>
                                                    <p className="text-xs text-muted-foreground">
                                                        {movement.type.label} ·{' '}
                                                        {movement.occurred_at}
                                                    </p>
                                                </div>
                                                <span
                                                    className={cn(
                                                        'shrink-0 text-sm font-medium tabular-nums crm-num',
                                                        movement.quantity > 0 &&
                                                            'text-success',
                                                        movement.quantity < 0 &&
                                                            'text-danger',
                                                    )}
                                                >
                                                    {movement.quantity > 0
                                                        ? '+'
                                                        : ''}
                                                    {movement.quantity}
                                                </span>
                                            </li>
                                        ))}
                                </ul>
                            )}
                        </SectionCard>
                    </div>
                </div>
            </div>
        </>
    );
}
