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 { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { motion } from "framer-motion";
import { Input } from "@/components/ui/input";
import config from "../config";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";

// Matches backend COLUMN_MAP keys for sorting
type BrandSortableColumns =
    | 'brandName' | 'productCount' | 'activeProductCount' | 'currentStockUnits'
    | 'currentStockCost' | 'currentStockRetail' | 'revenue_7d' | 'revenue_30d'
    | 'profit_30d' | 'sales_30d' | 'avg_margin_30d' | 'stock_turn_30d' 
    | 'salesGrowth30dVsPrev' | 'revenueGrowth30dVsPrev' | 'status';

interface BrandMetric {
    brand_id: string | number;
    brand_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;
    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;
    stock_turn_30d: string | number | null;
    // Growth metrics
    sales_growth_30d_vs_prev: string | number | null;
    revenue_growth_30d_vs_prev: string | number | null;
    status: string;
    brand_status: string;
    description: string;
    // Camel case versions
    brandId: string | number;
    brandName: string;
    lastCalculated: string;
    productCount: number;
    activeProductCount: number;
    replenishableProductCount: number;
    currentStockUnits: number;
    currentStockCost: string | number;
    currentStockRetail: string | number;
    lifetimeSales: number;
    lifetimeRevenue: string | number;
    avgMargin_30d: string | number | null;
    stockTurn_30d: string | number | null;
    salesGrowth30dVsPrev: string | number | null;
    revenueGrowth30dVsPrev: string | number | null;
}

// Define response type to avoid type errors
interface BrandResponse {
    brands: BrandMetric[];
    pagination: { 
        total: number; 
        pages: number; 
        currentPage: number; 
        limit: number; 
    };
}

interface BrandFilterOptions {
    statuses: string[];
}

interface BrandStats {
    totalBrands: number;
    activeBrands: number;
    totalActiveProducts: number; // SUM(active_product_count)
    totalValue: number; // SUM(current_stock_cost)
    avgMargin: number; // Weighted avg margin 30d
}

interface BrandFilters {
    search: string;
    status: string;
    showInactive: boolean; // Show brands with 0 active products
}

const ITEMS_PER_PAGE = 50;

// Re-use formatting helpers or define here
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)}%`;
};

// 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 Brands() {
    const [page, setPage] = useState(1);
    const [limit] = useState(ITEMS_PER_PAGE);
    const [sortColumn, setSortColumn] = useState<BrandSortableColumns>("brandName");
    const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
    const [filters, setFilters] = useState<BrandFilters>({
        search: "",
        status: "all",
        showInactive: false, // Default to hiding brands 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('brandName_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 brands with active products
        }
        // Add more filters here if needed (e.g., revenue30d_gt=5000)

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

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

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

    // Fetch filter options
    const { data: filterOptions } = useQuery<BrandFilterOptions, Error>({
        queryKey: ['brandsFilterOptions'],
        queryFn: async () => {
            const response = await fetch(`${config.apiUrl}/brands-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: BrandSortableColumns) => {
        setSortDirection(prev => (sortColumn === column && prev === "asc" ? "desc" : "asc"));
        setSortColumn(column);
        setPage(1);
    }, [sortColumn]);

    const handleFilterChange = useCallback((filterName: keyof BrandFilters, 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 brands = listData?.brands ?? [];
    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">Brands</h1>
                 <div className="text-sm text-muted-foreground">
                    {isLoadingList && !pagination ? 'Loading...' : `${formatNumber(pagination?.total)} brands`}
                </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 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>
            </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 brands..."
                    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-brands"
                        checked={filters.showInactive}
                        onCheckedChange={(checked) => handleFilterChange('showInactive', checked)}
                    />
                    <Label htmlFor="show-inactive-brands">Show brands with no active products</Label>
                </div>
            </div>

             {/* Data Table */}
             <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                             <TableHead onClick={() => handleSort("brandName")} className="cursor-pointer">Brand</TableHead>
                             <TableHead onClick={() => handleSort("activeProductCount")} className="cursor-pointer text-right">Active Prod.</TableHead>
                             <TableHead onClick={() => handleSort("currentStockUnits")} className="cursor-pointer text-right">Stock Units</TableHead>
                             <TableHead onClick={() => handleSort("currentStockCost")} className="cursor-pointer text-right">Stock Cost</TableHead>
                             <TableHead onClick={() => handleSort("currentStockRetail")} className="cursor-pointer text-right">Stock Retail</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("stock_turn_30d")} className="cursor-pointer text-right">Stock Turn (30d)</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-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-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={12} className="text-center py-8 text-destructive">
                                    Error loading brands: {listError.message}
                                </TableCell>
                            </TableRow>
                        ) : brands.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={12} className="text-center py-8 text-muted-foreground">
                                    No brands found matching your criteria.
                                </TableCell>
                            </TableRow>
                        ) : (
                            brands.map((brand: BrandMetric) => (
                                <TableRow key={brand.brand_id} className={brand.active_product_count === 0 ? "opacity-60" : ""}>
                                    <TableCell className="font-medium">{brand.brand_name}</TableCell>
                                    <TableCell className="text-right">{formatNumber(brand.active_product_count || brand.activeProductCount)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(brand.current_stock_units || brand.currentStockUnits)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.current_stock_cost as number)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.current_stock_retail as number)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.revenue_30d as number)}</TableCell>
                                    <TableCell className="text-right">{formatCurrency(brand.profit_30d as number)}</TableCell>
                                    <TableCell className="text-right">{formatPercentage(brand.avg_margin_30d as number)}</TableCell>
                                    <TableCell className="text-right">{formatNumber(brand.stock_turn_30d, 2)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(brand.sales_growth_30d_vs_prev)}</TableCell>
                                    <TableCell className="text-right">{formatGrowth(brand.revenue_growth_30d_vs_prev)}</TableCell>
                                    <TableCell className="text-right">
                                        <Badge variant={getStatusVariant(brand.status)}>
                                            {brand.status || 'Unknown'}
                                        </Badge>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

             {/* Pagination Controls */}
            {totalPages > 1 && pagination && (
                 <motion.div layout="position" transition={{ duration: 0.15 }} 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>
                </motion.div>
            )}
        </motion.div>
    );
}

export default Brands;