import { useState, useMemo, useCallback, type ReactNode } from "react";
import { apiFetch } from '@/utils/api';
import { useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
} from "@/components/ui/pagination";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import config from "../config";

// =========================================================================
// Types — camelCase only, matching backend COLUMN_MAP keys
// =========================================================================

interface BasePagination {
    total: number;
    pages: number;
    currentPage: number;
    limit: number;
}

interface BrandMetric {
    brandName: string;
    productCount: number;
    activeProductCount: number;
    currentStockUnits: number;
    currentStockCost: string | number;
    currentStockRetail: string | number;
    sales30d: number;
    revenue30d: string | number;
    profit30d: string | number;
    avgMargin30d: string | number | null;
    salesGrowth30dVsPrev: string | number | null;
    revenueGrowth30dVsPrev: string | number | null;
    brandStatus: string;
}

interface VendorMetric {
    vendorName: string;
    productCount: number;
    activeProductCount: number;
    currentStockCost: string | number;
    onOrderUnits: number;
    onOrderCost: string | number;
    avgLeadTimeDays: number | null;
    poCount365d: number;
    sales30d: number;
    revenue30d: string | number;
    profit30d: string | number;
    avgMargin30d: string | number | null;
    salesGrowth30dVsPrev: string | number | null;
    revenueGrowth30dVsPrev: string | number | null;
    vendorStatus: string;
}

interface BrandListResponse {
    brands: BrandMetric[];
    pagination: BasePagination;
}

interface VendorListResponse {
    vendors: VendorMetric[];
    pagination: BasePagination;
}

interface BrandStats {
    totalBrands: number;
    activeBrands: number;
    totalActiveProducts: number;
    totalValue: number;
    avgMargin: number;
}

interface VendorStats {
    totalVendors: number;
    activeVendors: number;
    totalActiveProducts: number;
    totalValue: number;
    totalOnOrderValue: number;
    avgLeadTime: number;
}

interface FilterOptions {
    statuses: string[];
}

interface AggregateFilters {
    search: string;
    status: string;
    showInactive: boolean;
}

type BrandSortableColumn =
    | "brandName"
    | "activeProductCount"
    | "currentStockUnits"
    | "currentStockCost"
    | "currentStockRetail"
    | "revenue30d"
    | "profit30d"
    | "avgMargin30d"
    | "salesGrowth30dVsPrev"
    | "revenueGrowth30dVsPrev"
    | "status";

type VendorSortableColumn =
    | "vendorName"
    | "activeProductCount"
    | "currentStockCost"
    | "onOrderUnits"
    | "onOrderCost"
    | "avgLeadTimeDays"
    | "revenue30d"
    | "profit30d"
    | "avgMargin30d"
    | "poCount365d"
    | "salesGrowth30dVsPrev"
    | "revenueGrowth30dVsPrev"
    | "status";

const ITEMS_PER_PAGE = 50;

// =========================================================================
// Formatters
// =========================================================================

const toNumber = (value: number | string | null | undefined): number | null => {
    if (value == null) return null;
    const n = typeof value === "string" ? parseFloat(value) : value;
    return Number.isFinite(n) ? n : null;
};

const formatCurrency = (value: number | string | null | undefined, digits = 0): string => {
    const n = toNumber(value);
    if (n === null) return "N/A";
    return new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
    }).format(n);
};

const formatNumber = (value: number | string | null | undefined, digits = 0): string => {
    const n = toNumber(value);
    if (n === null) return "N/A";
    return n.toLocaleString(undefined, {
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
    });
};

const formatPercentage = (value: number | string | null | undefined, digits = 1): string => {
    const n = toNumber(value);
    if (n === null) return "N/A";
    return `${n.toFixed(digits)}%`;
};

const formatDays = (value: number | string | null | undefined, digits = 1): string => {
    const n = toNumber(value);
    if (n === null) return "N/A";
    return `${n.toFixed(digits)} days`;
};

const formatGrowth = (value: number | string | null | undefined, digits = 1): ReactNode => {
    const n = toNumber(value);
    if (n === null) return <span className="text-muted-foreground">N/A</span>;
    const formatted = `${n >= 0 ? "+" : ""}${n.toFixed(digits)}%`;
    const colorClass = n >= 0 ? "text-green-600" : "text-red-600";
    return <span className={colorClass}>{formatted}</span>;
};

const getStatusVariant = (status: string): "default" | "secondary" | "outline" | "destructive" => {
    switch (status) {
        case "active":
            return "default";
        case "inactive":
            return "secondary";
        case "discontinued":
            return "destructive";
        default:
            return "outline";
    }
};

// =========================================================================
// Shared list hook — filters, sort, pagination, query
// =========================================================================

interface UseAggregateListOptions<TSort extends string> {
    endpoint: string;
    queryKeyPrefix: string;
    searchFilterKey: string; // e.g. "brandName_ilike"
    defaultSort: TSort;
}

function useAggregateList<TResponse, TSort extends string>(opts: UseAggregateListOptions<TSort>) {
    const [page, setPage] = useState(1);
    const [sortColumn, setSortColumn] = useState<TSort>(opts.defaultSort);
    const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
    const [filters, setFilters] = useState<AggregateFilters>({
        search: "",
        status: "all",
        showInactive: false,
    });

    const queryParams = useMemo(() => {
        const params = new URLSearchParams();
        params.set("page", page.toString());
        params.set("limit", ITEMS_PER_PAGE.toString());
        params.set("sort", sortColumn);
        params.set("order", sortDirection);
        if (filters.search) params.set(opts.searchFilterKey, filters.search);
        if (filters.status !== "all") params.set("status", filters.status);
        if (!filters.showInactive) params.set("activeProductCount_gt", "0");
        return params;
    }, [page, sortColumn, sortDirection, filters, opts.searchFilterKey]);

    const query = useQuery<TResponse, Error>({
        queryKey: [opts.queryKeyPrefix, queryParams.toString()],
        queryFn: async () => {
            const response = await apiFetch(`${config.apiUrl}/${opts.endpoint}?${queryParams.toString()}`, {
                credentials: "include",
            });
            if (!response.ok) throw new Error(`Network response was not ok (${response.status})`);
            return response.json();
        },
        placeholderData: (prev) => prev,
    });

    const handleSort = useCallback(
        (column: TSort) => {
            setSortDirection((prev) => (sortColumn === column && prev === "asc" ? "desc" : "asc"));
            setSortColumn(column);
            setPage(1);
        },
        [sortColumn],
    );

    const handleFilterChange = useCallback(
        <K extends keyof AggregateFilters>(key: K, value: AggregateFilters[K]) => {
            setFilters((prev) => ({ ...prev, [key]: value }));
            setPage(1);
        },
        [],
    );

    return {
        data: query.data,
        isLoading: query.isLoading,
        error: query.error,
        page,
        setPage,
        sortColumn,
        sortDirection,
        handleSort,
        filters,
        handleFilterChange,
    };
}

// =========================================================================
// Shared UI: FilterBar, PaginationBar, sortable header cell
// =========================================================================

interface FilterBarProps {
    searchPlaceholder: string;
    inactiveLabel: string;
    filters: AggregateFilters;
    onFilterChange: <K extends keyof AggregateFilters>(key: K, value: AggregateFilters[K]) => void;
    statuses?: string[];
    switchId: string;
}

function FilterBar({ searchPlaceholder, inactiveLabel, filters, onFilterChange, statuses, switchId }: FilterBarProps) {
    return (
        <div className="flex flex-wrap items-center space-y-2 sm:space-y-0 sm:space-x-2">
            <Input
                placeholder={searchPlaceholder}
                value={filters.search}
                onChange={(e) => onFilterChange("search", e.target.value)}
                className="w-full sm:w-[250px]"
            />
            <Select value={filters.status} onValueChange={(value) => onFilterChange("status", value)}>
                <SelectTrigger className="w-full sm:w-[180px]">
                    <SelectValue placeholder="Status" />
                </SelectTrigger>
                <SelectContent>
                    <SelectItem value="all">All Statuses</SelectItem>
                    {statuses?.map((status) => (
                        <SelectItem key={status} value={status}>
                            {status.charAt(0).toUpperCase() + status.slice(1)}
                        </SelectItem>
                    ))}
                </SelectContent>
            </Select>
            <div className="flex items-center space-x-2 ml-auto">
                <Switch
                    id={switchId}
                    checked={filters.showInactive}
                    onCheckedChange={(checked) => onFilterChange("showInactive", checked)}
                />
                <Label htmlFor={switchId}>{inactiveLabel}</Label>
            </div>
        </div>
    );
}

interface PaginationBarProps {
    pagination: BasePagination;
    onPageChange: (page: number) => void;
}

function PaginationBar({ pagination, onPageChange }: PaginationBarProps) {
    const totalPages = pagination.pages;
    if (totalPages <= 1) return null;
    const goTo = (newPage: number) => {
        if (newPage >= 1 && newPage <= totalPages) onPageChange(newPage);
    };
    return (
        <motion.div layout="position" transition={{ duration: 0.15 }} className="flex justify-center">
            <Pagination>
                <PaginationContent>
                    <PaginationItem>
                        <PaginationPrevious
                            href="#"
                            onClick={(e) => {
                                e.preventDefault();
                                goTo(pagination.currentPage - 1);
                            }}
                            aria-disabled={pagination.currentPage === 1}
                            className={pagination.currentPage === 1 ? "pointer-events-none opacity-50" : ""}
                        />
                    </PaginationItem>
                    {[...Array(totalPages)].map((_, i) => (
                        <PaginationItem key={i + 1}>
                            <PaginationLink
                                href="#"
                                onClick={(e) => {
                                    e.preventDefault();
                                    goTo(i + 1);
                                }}
                                isActive={pagination.currentPage === i + 1}
                            >
                                {i + 1}
                            </PaginationLink>
                        </PaginationItem>
                    ))}
                    <PaginationItem>
                        <PaginationNext
                            href="#"
                            onClick={(e) => {
                                e.preventDefault();
                                goTo(pagination.currentPage + 1);
                            }}
                            aria-disabled={pagination.currentPage >= totalPages}
                            className={pagination.currentPage >= totalPages ? "pointer-events-none opacity-50" : ""}
                        />
                    </PaginationItem>
                </PaginationContent>
            </Pagination>
        </motion.div>
    );
}

interface SortableHeadProps<TSort extends string> {
    column: TSort;
    label: string;
    activeColumn: TSort;
    direction: "asc" | "desc";
    onSort: (column: TSort) => void;
    align?: "left" | "right";
}

function SortableHead<TSort extends string>({
    column,
    label,
    activeColumn,
    direction,
    onSort,
    align = "left",
}: SortableHeadProps<TSort>) {
    const isActive = activeColumn === column;
    const indicator = isActive ? (direction === "asc" ? " ↑" : " ↓") : "";
    return (
        <TableHead onClick={() => onSort(column)} className={`cursor-pointer ${align === "right" ? "text-right" : ""}`}>
            {label}
            {indicator}
        </TableHead>
    );
}

// =========================================================================
// Brands tab
// =========================================================================

const BRAND_COLUMN_COUNT = 11;

function BrandsPanel() {
    const { data, isLoading, error, sortColumn, sortDirection, handleSort, filters, handleFilterChange, setPage } =
        useAggregateList<BrandListResponse, BrandSortableColumn>({
            endpoint: "brands-aggregate",
            queryKeyPrefix: "brands",
            searchFilterKey: "brandName_ilike",
            defaultSort: "brandName",
        });

    const { data: statsData, isLoading: isLoadingStats } = useQuery<BrandStats, Error>({
        queryKey: ["brandsStats"],
        queryFn: async () => {
            const response = await apiFetch(`${config.apiUrl}/brands-aggregate/stats`, { credentials: "include" });
            if (!response.ok) throw new Error("Failed to fetch brand stats");
            return response.json();
        },
    });

    const { data: filterOptions } = useQuery<FilterOptions, Error>({
        queryKey: ["brandsFilterOptions"],
        queryFn: async () => {
            const response = await apiFetch(`${config.apiUrl}/brands-aggregate/filter-options`, { credentials: "include" });
            if (!response.ok) throw new Error("Failed to fetch filter options");
            return response.json();
        },
    });

    const brands = data?.brands ?? [];
    const pagination = data?.pagination;

    const head = (col: BrandSortableColumn, label: string, align: "left" | "right" = "left") => (
        <SortableHead
            column={col}
            label={label}
            activeColumn={sortColumn}
            direction={sortDirection}
            onSort={handleSort}
            align={align}
        />
    );

    return (
        <motion.div layout transition={{ layout: { duration: 0.15, ease: [0.4, 0, 0.2, 1] } }} className="space-y-4">
            <div className="flex justify-end text-sm text-muted-foreground">
                {isLoading && !pagination ? "Loading..." : `${formatNumber(pagination?.total)} brands`}
            </div>

            {/* Stats */}
            <div className="grid gap-4 md:grid-cols-4">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Brands</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-24" />
                        ) : (
                            <div className="text-2xl font-bold">{formatNumber(statsData?.totalBrands)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">
                            {isLoadingStats ? (
                                <Skeleton className="h-4 w-28" />
                            ) : (
                                `${formatNumber(statsData?.activeBrands)} active`
                            )}
                        </p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Stock Value</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-28" />
                        ) : (
                            <div className="text-2xl font-bold">{formatCurrency(statsData?.totalValue)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">Current cost value</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Avg Margin (30d)</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-20" />
                        ) : (
                            <div className="text-2xl font-bold">{formatPercentage(statsData?.avgMargin)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">Weighted by revenue</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Active Products</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-24" />
                        ) : (
                            <div className="text-2xl font-bold">{formatNumber(statsData?.totalActiveProducts)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">Across all brands</p>
                    </CardContent>
                </Card>
            </div>

            {/* Filters */}
            <FilterBar
                searchPlaceholder="Search brands..."
                inactiveLabel="Show brands with no active products"
                filters={filters}
                onFilterChange={handleFilterChange}
                statuses={filterOptions?.statuses}
                switchId="show-inactive-brands"
            />

            {/* Table */}
            <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            {head("brandName", "Brand")}
                            {head("activeProductCount", "Active Prod.", "right")}
                            {head("currentStockUnits", "Stock Units", "right")}
                            {head("currentStockCost", "Stock Cost", "right")}
                            {head("currentStockRetail", "Stock Retail", "right")}
                            {head("revenue30d", "Revenue (30d)", "right")}
                            {head("profit30d", "Profit (30d)", "right")}
                            {head("avgMargin30d", "Margin (30d)", "right")}
                            {head("salesGrowth30dVsPrev", "Sales Growth", "right")}
                            {head("revenueGrowth30dVsPrev", "Revenue Growth", "right")}
                            {head("status", "Status", "right")}
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {isLoading && !data ? (
                            Array.from({ length: 5 }).map((_, i) => (
                                <TableRow key={`skel-${i}`}>
                                    {Array.from({ length: BRAND_COLUMN_COUNT }).map((_, j) => (
                                        <TableCell key={j} className={j === 0 ? "" : "text-right"}>
                                            <Skeleton className={`h-5 ${j === 0 ? "w-40" : "w-16 ml-auto"}`} />
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))
                        ) : error ? (
                            <TableRow>
                                <TableCell colSpan={BRAND_COLUMN_COUNT} className="text-center py-8 text-destructive">
                                    Error loading brands: {error.message}
                                </TableCell>
                            </TableRow>
                        ) : brands.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={BRAND_COLUMN_COUNT} className="text-center py-8 text-muted-foreground">
                                    No brands found matching your criteria.
                                </TableCell>
                            </TableRow>
                        ) : (
                            brands.map((brand) => (
                                <TableRow
                                    key={brand.brandName}
                                    className={brand.activeProductCount === 0 ? "opacity-60" : ""}
                                >
                                    <TableCell className="font-medium">{brand.brandName}</TableCell>
                                    <TableCell className="text-right">{formatNumber(brand.activeProductCount)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(brand.currentStockUnits)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.currentStockCost)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.currentStockRetail)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.revenue30d)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.profit30d)}</TableCell>
                                    <TableCell className="text-right">{formatPercentage(brand.avgMargin30d)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(brand.salesGrowth30dVsPrev)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(brand.revenueGrowth30dVsPrev)}</TableCell>
                                    <TableCell className="text-right">
                                        <Badge variant={getStatusVariant(brand.brandStatus)}>
                                            {brand.brandStatus || "Unknown"}
                                        </Badge>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {pagination && <PaginationBar pagination={pagination} onPageChange={setPage} />}
        </motion.div>
    );
}

// =========================================================================
// Vendors tab
// =========================================================================

const VENDOR_COLUMN_COUNT = 13;

function VendorsPanel() {
    const { data, isLoading, error, sortColumn, sortDirection, handleSort, filters, handleFilterChange, setPage } =
        useAggregateList<VendorListResponse, VendorSortableColumn>({
            endpoint: "vendors-aggregate",
            queryKeyPrefix: "vendors",
            searchFilterKey: "vendorName_ilike",
            defaultSort: "vendorName",
        });

    const { data: statsData, isLoading: isLoadingStats } = useQuery<VendorStats, Error>({
        queryKey: ["vendorsStats"],
        queryFn: async () => {
            const response = await apiFetch(`${config.apiUrl}/vendors-aggregate/stats`, { credentials: "include" });
            if (!response.ok) throw new Error("Failed to fetch vendor stats");
            return response.json();
        },
    });

    const { data: filterOptions } = useQuery<FilterOptions, Error>({
        queryKey: ["vendorsFilterOptions"],
        queryFn: async () => {
            const response = await apiFetch(`${config.apiUrl}/vendors-aggregate/filter-options`, { credentials: "include" });
            if (!response.ok) throw new Error("Failed to fetch filter options");
            return response.json();
        },
    });

    const vendors = data?.vendors ?? [];
    const pagination = data?.pagination;

    const head = (col: VendorSortableColumn, label: string, align: "left" | "right" = "left") => (
        <SortableHead
            column={col}
            label={label}
            activeColumn={sortColumn}
            direction={sortDirection}
            onSort={handleSort}
            align={align}
        />
    );

    return (
        <motion.div layout transition={{ layout: { duration: 0.15, ease: [0.4, 0, 0.2, 1] } }} className="space-y-4">
            <div className="flex justify-end text-sm text-muted-foreground">
                {isLoading && !pagination ? "Loading..." : `${formatNumber(pagination?.total)} vendors`}
            </div>

            {/* Stats */}
            <div className="grid gap-4 md:grid-cols-4">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Vendors</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-24" />
                        ) : (
                            <div className="text-2xl font-bold">{formatNumber(statsData?.totalVendors)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">
                            {isLoadingStats ? (
                                <Skeleton className="h-4 w-28" />
                            ) : (
                                `${formatNumber(statsData?.activeVendors)} active`
                            )}
                        </p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Stock Value</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-28" />
                        ) : (
                            <div className="text-2xl font-bold">{formatCurrency(statsData?.totalValue)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">Current cost value</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Value On Order</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-28" />
                        ) : (
                            <div className="text-2xl font-bold">{formatCurrency(statsData?.totalOnOrderValue)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">Total cost on open POs</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Avg Lead Time</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isLoadingStats ? (
                            <Skeleton className="h-8 w-20" />
                        ) : (
                            <div className="text-2xl font-bold">{formatDays(statsData?.avgLeadTime)}</div>
                        )}
                        <p className="text-xs text-muted-foreground">Average across vendors</p>
                    </CardContent>
                </Card>
            </div>

            {/* Filters */}
            <FilterBar
                searchPlaceholder="Search vendors..."
                inactiveLabel="Show vendors with no active products"
                filters={filters}
                onFilterChange={handleFilterChange}
                statuses={filterOptions?.statuses}
                switchId="show-inactive-vendors"
            />

            {/* Table */}
            <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            {head("vendorName", "Vendor")}
                            {head("activeProductCount", "Active Prod.", "right")}
                            {head("currentStockCost", "Stock Value", "right")}
                            {head("onOrderUnits", "On Order (Units)", "right")}
                            {head("onOrderCost", "On Order (Cost)", "right")}
                            {head("avgLeadTimeDays", "Avg Lead Time", "right")}
                            {head("revenue30d", "Revenue (30d)", "right")}
                            {head("profit30d", "Profit (30d)", "right")}
                            {head("avgMargin30d", "Margin (30d)", "right")}
                            {head("poCount365d", "POs (365d)", "right")}
                            {head("salesGrowth30dVsPrev", "Sales Growth", "right")}
                            {head("revenueGrowth30dVsPrev", "Revenue Growth", "right")}
                            {head("status", "Status", "right")}
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {isLoading && !data ? (
                            Array.from({ length: 5 }).map((_, i) => (
                                <TableRow key={`skel-${i}`}>
                                    {Array.from({ length: VENDOR_COLUMN_COUNT }).map((_, j) => (
                                        <TableCell key={j} className={j === 0 ? "" : "text-right"}>
                                            <Skeleton className={`h-5 ${j === 0 ? "w-40" : "w-16 ml-auto"}`} />
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))
                        ) : error ? (
                            <TableRow>
                                <TableCell colSpan={VENDOR_COLUMN_COUNT} className="text-center py-8 text-destructive">
                                    Error loading vendors: {error.message}
                                </TableCell>
                            </TableRow>
                        ) : vendors.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={VENDOR_COLUMN_COUNT} className="text-center py-8 text-muted-foreground">
                                    No vendors found matching your criteria.
                                </TableCell>
                            </TableRow>
                        ) : (
                            vendors.map((vendor) => (
                                <TableRow
                                    key={vendor.vendorName}
                                    className={vendor.activeProductCount === 0 ? "opacity-60" : ""}
                                >
                                    <TableCell className="font-medium">{vendor.vendorName}</TableCell>
                                    <TableCell className="text-right">{formatNumber(vendor.activeProductCount)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.currentStockCost)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(vendor.onOrderUnits)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.onOrderCost)}</TableCell>
                                    <TableCell className="text-right">{formatDays(vendor.avgLeadTimeDays)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.revenue30d)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.profit30d)}</TableCell>
                                    <TableCell className="text-right">{formatPercentage(vendor.avgMargin30d)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(vendor.poCount365d)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(vendor.salesGrowth30dVsPrev)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(vendor.revenueGrowth30dVsPrev)}</TableCell>
                                    <TableCell className="text-right">
                                        <Badge variant={getStatusVariant(vendor.vendorStatus)}>
                                            {vendor.vendorStatus || "Unknown"}
                                        </Badge>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {pagination && <PaginationBar pagination={pagination} onPageChange={setPage} />}
        </motion.div>
    );
}

// =========================================================================
// Top-level page
// =========================================================================

export function Brands() {
    const [tab, setTab] = useState<"brands" | "vendors">("brands");

    return (
        <div className="container mx-auto py-6 space-y-4">
            <h1 className="text-3xl font-bold tracking-tight">
                {tab === "brands" ? "Brands" : "Vendors"}
            </h1>

            <Tabs value={tab} onValueChange={(v) => setTab(v as "brands" | "vendors")}>
                <TabsList>
                    <TabsTrigger value="brands">Brands</TabsTrigger>
                    <TabsTrigger value="vendors">Vendors</TabsTrigger>
                </TabsList>

                <TabsContent value="brands" className="mt-4">
                    <BrandsPanel />
                </TabsContent>
                <TabsContent value="vendors" className="mt-4">
                    <VendorsPanel />
                </TabsContent>
            </Tabs>
        </div>
    );
}

export default Brands;
