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

// Matches backend COLUMN_MAP keys for sorting
type VendorSortableColumns =
    | 'vendorName' | 'productCount' | 'activeProductCount' | 'currentStockUnits'
    | 'currentStockCost' | 'onOrderUnits' | 'onOrderCost' | 'avgLeadTimeDays'
    | 'revenue_30d' | 'profit_30d' | 'avg_margin_30d' | 'po_count_365d' 
    | 'salesGrowth30dVsPrev' | 'revenueGrowth30dVsPrev' | 'status';

interface VendorMetric {
    vendor_id: string | number;
    vendor_name: string;
    last_calculated: string;
    product_count: number;
    active_product_count: number;
    replenishable_product_count: number;
    current_stock_units: number;
    current_stock_cost: string | number;
    current_stock_retail: string | number;
    on_order_units: number;
    on_order_cost: string | number;
    po_count_365d: number;
    avg_lead_time_days: number | null;
    sales_7d: number;
    revenue_7d: string | number;
    sales_30d: number;
    revenue_30d: string | number;
    profit_30d: string | number;
    cogs_30d: string | number;
    sales_365d: number;
    revenue_365d: string | number;
    lifetime_sales: number;
    lifetime_revenue: string | number;
    avg_margin_30d: string | number | null;
    // Growth metrics
    sales_growth_30d_vs_prev: string | number | null;
    revenue_growth_30d_vs_prev: string | number | null;
    // New fields added by vendorsAggregate
    status: string;
    vendor_status: string;
    cost_metrics_30d: {
        avg_unit_cost: number;
        total_spend: number;
        order_count: number;
    };
    // Camel case versions
    vendorId: string | number;
    vendorName: string;
    lastCalculated: string;
    productCount: number;
    activeProductCount: number;
    replenishableProductCount: number;
    currentStockUnits: number;
    currentStockCost: string | number;
    currentStockRetail: string | number;
    onOrderUnits: number;
    onOrderCost: string | number;
    poCount_365d: number;
    avgLeadTimeDays: number | null;
    lifetimeSales: number;
    lifetimeRevenue: string | number;
    avgMargin_30d: string | number | null;
    salesGrowth30dVsPrev: string | number | null;
    revenueGrowth30dVsPrev: string | number | null;
}

// Define response type to avoid type errors
interface VendorResponse {
    vendors: VendorMetric[];
    pagination: { 
        total: number; 
        pages: number; 
        currentPage: number; 
        limit: number; 
    };
}

interface VendorFilterOptions {
    statuses: string[];
}

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

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

const ITEMS_PER_PAGE = 50;

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

const formatNumber = (value: number | string | null | undefined, digits = 0): string => {
    if (value == null) return 'N/A';
    if (typeof value === 'string') {
        const parsed = parseFloat(value);
        if (isNaN(parsed)) return 'N/A';
        return parsed.toLocaleString(undefined, {
            minimumFractionDigits: digits,
            maximumFractionDigits: digits,
        });
    }
    if (typeof value !== 'number' || isNaN(value)) return 'N/A';
    return value.toLocaleString(undefined, {
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
    });
};

const formatPercentage = (value: number | string | null | undefined, digits = 1): string => {
    if (value == null) return 'N/A';
    if (typeof value === 'string') {
        const parsed = parseFloat(value);
        if (isNaN(parsed)) return 'N/A';
        return `${parsed.toFixed(digits)}%`;
    }
    if (typeof value !== 'number' || isNaN(value)) return 'N/A';
    return `${value.toFixed(digits)}%`;
};

const formatDays = (value: number | string | null | undefined, digits = 1): string => {
    if (value == null) return 'N/A';
    if (typeof value === 'string') {
        const parsed = parseFloat(value);
        if (isNaN(parsed)) return 'N/A';
        return `${parsed.toFixed(digits)} days`;
    }
    if (typeof value !== 'number' || isNaN(value)) return 'N/A';
    return `${value.toFixed(digits)} days`;
};

// Growth formatting with color coding
const formatGrowth = (value: number | string | null | undefined, digits = 1) => {
    if (value == null) return <span className="text-muted-foreground">N/A</span>;
    
    const numValue = typeof value === "string" ? parseFloat(value) : value;
    if (isNaN(numValue)) return <span className="text-muted-foreground">N/A</span>;
    
    const formatted = `${numValue >= 0 ? '+' : ''}${numValue.toFixed(digits)}%`;
    const colorClass = numValue >= 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';
    }
};

export function Vendors() {
    const [page, setPage] = useState(1);
    const [limit] = useState(ITEMS_PER_PAGE);
    const [sortColumn, setSortColumn] = useState<VendorSortableColumns>("vendorName");
    const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
    const [filters, setFilters] = useState<VendorFilters>({
        search: "",
        status: "all",
        showInactive: false, // Default to hiding vendors with 0 active products
    });

    // --- Data Fetching ---

    const queryParams = useMemo(() => {
        const params = new URLSearchParams();
        params.set('page', page.toString());
        params.set('limit', limit.toString());
        params.set('sort', sortColumn);
        params.set('order', sortDirection);

        if (filters.search) {
            params.set('vendorName_ilike', filters.search); // Filter by name
        }
        if (filters.status !== 'all') {
            params.set('status', filters.status); // Filter by status
        }
        if (!filters.showInactive) {
            params.set('activeProductCount_gt', '0'); // Only show vendors with active products
        }

        return params;
    }, [page, limit, sortColumn, sortDirection, filters]);

    const { data: listData, isLoading: isLoadingList, error: listError } = useQuery<VendorResponse, Error>({
        queryKey: ['vendors', queryParams.toString()],
        queryFn: async () => {
            const response = await fetch(`${config.apiUrl}/vendors-aggregate?${queryParams.toString()}`, {
                credentials: 'include'
            });
            if (!response.ok) throw new Error(`Network response was not ok (${response.status})`);
            return response.json();
        },
        placeholderData: (prev) => prev, // Modern replacement for keepPreviousData
    });

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

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

    // --- Event Handlers ---

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

    const handleFilterChange = useCallback((filterName: keyof VendorFilters, value: string | boolean) => {
        setFilters(prev => ({ ...prev, [filterName]: value }));
        setPage(1);
    }, []);

     const handlePageChange = (newPage: number) => {
        if (newPage >= 1 && newPage <= (listData?.pagination.pages ?? 1)) {
            setPage(newPage);
        }
    };

    // --- Derived Data ---
    const vendors = listData?.vendors ?? [];
    const pagination = listData?.pagination;
    const totalPages = pagination?.pages ?? 0;

    // --- Rendering ---

    return (
        <motion.div
            layout
            transition={{ layout: { duration: 0.15, ease: [0.4, 0, 0.2, 1] } }}
            className="container mx-auto py-6 space-y-4"
        >
            {/* Header */}
            <motion.div layout="position" transition={{ duration: 0.15 }} className="flex items-center justify-between">
                <h1 className="text-3xl font-bold tracking-tight">Vendors</h1>
                 <div className="text-sm text-muted-foreground">
                    {isLoadingList && !pagination ? 'Loading...' : `${formatNumber(pagination?.total)} vendors`}
                </div>
            </motion.div>

            {/* Stats Cards */}
            <motion.div layout="preserve-aspect" transition={{ duration: 0.15 }} 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>
            </motion.div>

            {/* Filter Controls */}
            <div className="flex flex-wrap items-center space-y-2 sm:space-y-0 sm:space-x-2">
                <Input
                    placeholder="Search vendors..."
                    value={filters.search}
                    onChange={(e) => handleFilterChange('search', e.target.value)}
                    className="w-full sm:w-[250px]"
                />
                <Select
                    value={filters.status}
                    onValueChange={(value) => handleFilterChange('status', value)}
                >
                    <SelectTrigger className="w-full sm:w-[180px]">
                        <SelectValue placeholder="Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">All Statuses</SelectItem>
                        {filterOptions?.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="show-inactive-vendors"
                        checked={filters.showInactive}
                        onCheckedChange={(checked) => handleFilterChange('showInactive', checked)}
                    />
                    <Label htmlFor="show-inactive-vendors">Show vendors with no active products</Label>
                </div>
            </div>

            {/* Data Table */}
            <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead onClick={() => handleSort("vendorName")} className="cursor-pointer">Vendor</TableHead>
                            <TableHead onClick={() => handleSort("activeProductCount")} className="cursor-pointer text-right">Active Prod.</TableHead>
                            <TableHead onClick={() => handleSort("currentStockCost")} className="cursor-pointer text-right">Stock Value</TableHead>
                            <TableHead onClick={() => handleSort("onOrderUnits")} className="cursor-pointer text-right">On Order (Units)</TableHead>
                            <TableHead onClick={() => handleSort("onOrderCost")} className="cursor-pointer text-right">On Order (Cost)</TableHead>
                            <TableHead onClick={() => handleSort("avgLeadTimeDays")} className="cursor-pointer text-right">Avg Lead Time</TableHead>
                            <TableHead onClick={() => handleSort("revenue_30d")} className="cursor-pointer text-right">Revenue (30d)</TableHead>
                            <TableHead onClick={() => handleSort("profit_30d")} className="cursor-pointer text-right">Profit (30d)</TableHead>
                            <TableHead onClick={() => handleSort("avg_margin_30d")} className="cursor-pointer text-right">Margin (30d)</TableHead>
                            <TableHead onClick={() => handleSort("po_count_365d")} className="cursor-pointer text-right">POs (365d)</TableHead>
                            <TableHead onClick={() => handleSort("salesGrowth30dVsPrev")} className="cursor-pointer text-right">Sales Growth</TableHead>
                            <TableHead onClick={() => handleSort("revenueGrowth30dVsPrev")} className="cursor-pointer text-right">Revenue Growth</TableHead>
                            <TableHead onClick={() => handleSort("status")} className="cursor-pointer text-right">Status</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {isLoadingList && !listData ? (
                            Array.from({ length: 5 }).map((_, i) => ( // Skeleton rows
                                <TableRow key={`skel-${i}`}>
                                    <TableCell><Skeleton className="h-5 w-40" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-16 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-20 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-20 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-20 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-20 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-20 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-20 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-16 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-16 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-16 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-16 ml-auto" /></TableCell>
                                    <TableCell className="text-right"><Skeleton className="h-5 w-16 ml-auto" /></TableCell>
                                </TableRow>
                            ))
                        ) : listError ? (
                            <TableRow>
                                <TableCell colSpan={13} className="text-center py-8 text-destructive">
                                    Error loading vendors: {listError.message}
                                </TableCell>
                            </TableRow>
                        ) : vendors.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={13} className="text-center py-8 text-muted-foreground">
                                    No vendors found matching your criteria.
                                </TableCell>
                            </TableRow>
                        ) : (
                            vendors.map((vendor: VendorMetric) => (
                                <TableRow key={vendor.vendor_id} className={vendor.active_product_count === 0 ? "opacity-60" : ""}>
                                    <TableCell className="font-medium">{vendor.vendor_name}</TableCell>
                                    <TableCell className="text-right">{formatNumber(vendor.active_product_count || vendor.activeProductCount)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.current_stock_cost as number)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(vendor.on_order_units || vendor.onOrderUnits)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.on_order_cost as number)}</TableCell>
                                    <TableCell className="text-right">{formatDays(vendor.avg_lead_time_days || vendor.avgLeadTimeDays)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.revenue_30d as number)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(vendor.profit_30d as number)}</TableCell>
                                    <TableCell className="text-right">{formatPercentage(vendor.avg_margin_30d as number)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(vendor.po_count_365d || vendor.poCount_365d)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(vendor.sales_growth_30d_vs_prev)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(vendor.revenue_growth_30d_vs_prev)}</TableCell>
                                    <TableCell className="text-right">
                                        <Badge variant={getStatusVariant(vendor.status)}>
                                            {vendor.status || 'Unknown'}
                                        </Badge>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {/* Pagination Controls */}
            {totalPages > 1 && pagination && (
                <div className="flex justify-center">
                    <Pagination>
                        <PaginationContent>
                            <PaginationItem>
                                <PaginationPrevious
                                    href="#"
                                    onClick={(e) => { e.preventDefault(); handlePageChange(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(); handlePageChange(i + 1); }}
                                        isActive={pagination.currentPage === i + 1}
                                    >
                                        {i + 1}
                                    </PaginationLink>
                                </PaginationItem>
                            ))}
                            <PaginationItem>
                                <PaginationNext
                                    href="#"
                                    onClick={(e) => { e.preventDefault(); handlePageChange(pagination.currentPage + 1); }}
                                    aria-disabled={pagination.currentPage >= totalPages}
                                    className={pagination.currentPage >= totalPages ? "pointer-events-none opacity-50" : ""}
                                />
                            </PaginationItem>
                        </PaginationContent>
                    </Pagination>
                </div>
            )}
        </motion.div>
    );
}

export default Vendors;