import React, { useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { TrendingUp, Save, BarChart3, RefreshCw, ArrowUpRight, ArrowDownRight } from "lucide-react";
import { toast } from "sonner";
import { useSalesProjection } from "@/hooks/useSalesProjection";
import { SalesProjectionAPI } from "@/apis/SalesProjectionAPI";

export default function SalesProjectionPage() {
    const COMPARISON_MONTHS = 4;

    const {
      selectedCompany,
      selectedYear,
      projections,
      editingProjections,
      months,
      summary,
      isSaving,
      setSelectedYear,
      getValue,
      getTotalYear,
      saveProjection,
      handleMonthChange,
    } = useSalesProjection();

    const [comparison, setComparison] = useState(null);
    const [comparisonLoading, setComparisonLoading] = useState(false);
    const [comparisonTagFilter, setComparisonTagFilter] = useState("all");
    const [comparisonSecondaryTagFilter, setComparisonSecondaryTagFilter] = useState("all");
    const [comparisonTopMode, setComparisonTopMode] = useState("DOWN");
    const [comparisonTopLimit, setComparisonTopLimit] = useState("all");
    const [comparisonSearch, setComparisonSearch] = useState("");
    const [comparisonLineFilter, setComparisonLineFilter] = useState("all");
    const [operationalComparison, setOperationalComparison] = useState(null);
    const [operationalLoading, setOperationalLoading] = useState(false);
    const operationalMonth = new Date().getMonth() + 1;
    const [operationalTagFilter, setOperationalTagFilter] = useState("all");
    const [operationalPriorityFilter, setOperationalPriorityFilter] = useState("all");
    const [operationalTopLimit, setOperationalTopLimit] = useState("50");
    const [operationalSearch, setOperationalSearch] = useState("");
    const [operationalLineFilter, setOperationalLineFilter] = useState("all");
    const [searchTerm, setSearchTerm] = useState("");
    const [pageSize, setPageSize] = useState(25);
    const [page, setPage] = useState(1);
    const [essenceProjection, setEssenceProjection] = useState(null);
    const [essenceLoading, setEssenceLoading] = useState(false);
    const [projectionView, setProjectionView] = useState("units");

    const filteredProjections = useMemo(() => {
        const query = searchTerm.trim().toLowerCase();
        if (!query) return projections;
        return projections.filter((projection) =>
            `${projection.sku || ""} ${projection.product_name || ""}`.toLowerCase().includes(query),
        );
    }, [projections, searchTerm]);

    const totalPages = Math.max(1, Math.ceil(filteredProjections.length / pageSize));
    const safePage = Math.min(page, totalPages);
    const pageStart = (safePage - 1) * pageSize;
    const pagedProjections = filteredProjections.slice(pageStart, pageStart + pageSize);

    const loadComparison = async () => {
        if (!selectedCompany?.id) return;
        try {
            setComparisonLoading(true);
            const data = await SalesProjectionAPI.getComparison(
                String(selectedCompany.id),
                COMPARISON_MONTHS,
                undefined,
                Number(selectedYear),
                Number(operationalMonth),
            );
            setComparison(data || null);
        } catch (e) {
            toast.error("No se pudo cargar la comparativa: " + (e?.message || ""));
        } finally {
            setComparisonLoading(false);
        }
    };

    const loadOperationalComparison = async () => {
        if (!selectedCompany?.id || !selectedYear || !operationalMonth) return;
        try {
            setOperationalLoading(true);
            const data = await SalesProjectionAPI.getOperationalComparison(
                String(selectedCompany.id),
                Number(selectedYear),
                Number(operationalMonth),
                300,
            );
            setOperationalComparison(data || null);
        } catch (e) {
            toast.error("No se pudo cargar comparativa operativa: " + (e?.message || ""));
        } finally {
            setOperationalLoading(false);
        }
    };

    const loadEssenceProjection = async () => {
        if (!selectedCompany?.id || !selectedYear) return;
        try {
            setEssenceLoading(true);
            const data = await SalesProjectionAPI.getEssenceProjection(
                String(selectedCompany.id),
                Number(selectedYear),
            );
            setEssenceProjection(data || null);
        } catch (e) {
            toast.error("No se pudo cargar proyección por esencia: " + (e?.message || ""));
        } finally {
            setEssenceLoading(false);
        }
    };

    useEffect(() => {
        loadComparison();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedCompany?.id, selectedYear, operationalMonth]);

    useEffect(() => {
        loadOperationalComparison();
        loadEssenceProjection();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedCompany?.id, selectedYear, operationalMonth]);

    useEffect(() => {
        setPage(1);
    }, [searchTerm, selectedYear, pageSize]);

    const monthsLabel = { 1: "Ene", 2: "Feb", 3: "Mar", 4: "Abr", 5: "May", 6: "Jun", 7: "Jul", 8: "Ago", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dic" };

    const fallbackComparisonPeriods = useMemo(() => {
        if (comparison?.periods?.length) return comparison.periods;
        const anchorYear = Number(selectedYear) || new Date().getFullYear();
        const anchorMonth = Number(operationalMonth) || new Date().getMonth() + 1;
        // Para comparativa histórica mostramos meses cerrados previos al mes foco.
        const anchorDate = new Date(anchorYear, anchorMonth - 2, 1);
        const periods = [];
        for (let i = COMPARISON_MONTHS - 1; i >= 0; i -= 1) {
            const d = new Date(anchorDate.getFullYear(), anchorDate.getMonth() - i, 1);
            periods.push({ year: d.getFullYear(), month: d.getMonth() + 1 });
        }
        return periods;
    }, [comparison?.periods, selectedYear, operationalMonth]);

    const getComparisonTag = (cells = []) => {
        const variancePctValues = cells
            .map((cell) => (cell.variance_pct == null ? null : Number(cell.variance_pct)))
            .filter((value) => value !== null);

        if (!variancePctValues.length) return "SIN_DATA_HISTORICA";
        const avg = variancePctValues.reduce((acc, value) => acc + value, 0) / variancePctValues.length;
        if (avg <= -10) return "CAIDA_DEMANDA";
        if (avg >= 10) return "ALZA_DEMANDA";
        return "ESTABLE";
    };

    const getComparisonSecondaryTag = (cells = []) => {
        const variancePctValues = cells
            .map((cell) => (cell.variance_pct == null ? null : Number(cell.variance_pct)))
            .filter((value) => value !== null);
        if (variancePctValues.length < 3) return null;

        const signs = variancePctValues.map((value) => (value > 0 ? 1 : value < 0 ? -1 : 0));
        let signChanges = 0;
        for (let i = 1; i < signs.length; i += 1) {
            if (signs[i] !== 0 && signs[i - 1] !== 0 && signs[i] !== signs[i - 1]) signChanges += 1;
        }
        const spread = Math.max(...variancePctValues) - Math.min(...variancePctValues);

        if (signChanges >= 2 || spread >= 40) return "VOLATIL";
        return null;
    };

    const getLineFromSku = (sku) => {
        const value = String(sku || "").trim();
        if (!value) return "SIN_LINEA";
        const token = value.split(/[-_\s/]/)[0]?.trim();
        return token || "SIN_LINEA";
    };

    const comparisonRowsPrepared = useMemo(() => {
        const rows = (comparison?.rows || []).map((row) => {
            const tag = getComparisonTag(row.cells || []);
            const secondaryTag = getComparisonSecondaryTag(row.cells || []);
            const pctValues = (row.cells || []).map((cell) => Number(cell.variance_pct || 0));
            const maxUpDeviation = Math.max(0, ...pctValues);
            const maxDownDeviation = Math.min(0, ...pctValues);
            const maxAbsDeviation = Math.max(0, ...pctValues.map((value) => Math.abs(value)));
            let deviationScore = maxAbsDeviation;
            if (comparisonTopMode === "UP") deviationScore = maxUpDeviation;
            if (comparisonTopMode === "DOWN") deviationScore = Math.abs(maxDownDeviation);
            return {
                ...row,
                comparisonTag: tag,
                comparisonSecondaryTag: secondaryTag,
                maxUpDeviation,
                maxDownDeviation,
                maxAbsDeviation,
                deviationScore,
                line: getLineFromSku(row.sku),
            };
        });

        let filtered = rows;
        const query = comparisonSearch.trim().toLowerCase();
        if (query) {
            filtered = filtered.filter((row) =>
                `${row.sku || ""} ${row.name || ""}`.toLowerCase().includes(query),
            );
        }
        if (comparisonLineFilter !== "all") {
            filtered = filtered.filter((row) => row.line === comparisonLineFilter);
        }
        if (comparisonTagFilter !== "all") {
            filtered = filtered.filter((row) => row.comparisonTag === comparisonTagFilter);
        }
        if (comparisonSecondaryTagFilter === "VOLATIL") {
            filtered = filtered.filter((row) => row.comparisonSecondaryTag === "VOLATIL");
        } else if (comparisonSecondaryTagFilter === "NO_VOLATIL") {
            filtered = filtered.filter((row) => row.comparisonSecondaryTag !== "VOLATIL");
        }
        if (comparisonTopMode === "UP") {
            filtered = filtered.filter((row) => row.maxUpDeviation > 0);
        } else if (comparisonTopMode === "DOWN") {
            filtered = filtered.filter((row) => row.maxDownDeviation < 0);
        }
        filtered = [...filtered].sort((a, b) => b.deviationScore - a.deviationScore);
        if (comparisonTopLimit !== "all") {
            const n = Number(comparisonTopLimit);
            if (!Number.isNaN(n) && n > 0) filtered = filtered.slice(0, n);
        }
        return filtered;
    }, [
        comparison?.rows,
        comparisonSearch,
        comparisonLineFilter,
        comparisonTagFilter,
        comparisonSecondaryTagFilter,
        comparisonTopLimit,
        comparisonTopMode,
    ]);

    const comparisonLineOptions = useMemo(() => {
        const source = comparison?.rows || [];
        const lines = Array.from(
            new Set(source.map((row) => getLineFromSku(row.sku)).filter(Boolean)),
        ).sort((a, b) => a.localeCompare(b));
        return lines;
    }, [comparison?.rows]);

    const getOperationalTag = (row) => {
        if (!row.has_sales_data || !row.has_stock_data || !row.has_production_data) {
            return "SIN_DATA_OPERATIVA";
        }
        const projected = Number(row.projected || 0);
        const sold = Number(row.sold || 0);
        const closingStock = Number(row.closing_stock || 0);
        const required = Number(row.required_production || 0);

        if (required > 0 && (closingStock <= 0 || (projected > 0 && closingStock / projected <= 0.2))) {
            return "URGENTE_PRODUCIR";
        }
        if (closingStock <= 0 || (projected > 0 && closingStock / projected <= 0.1)) {
            return "RIESGO_QUIEBRE";
        }
        if (projected > 0 && closingStock / projected >= 1.5 && sold < projected * 0.6) {
            return "SOBRE_STOCK";
        }
        return "EN_RANGO";
    };

    const getOperationalPriority = (row, tag) => {
        const required = Number(row.required_production || 0);
        if (tag === "URGENTE_PRODUCIR" || tag === "RIESGO_QUIEBRE") return "ALTA";
        if (tag === "SOBRE_STOCK" || required > 0) return "MEDIA";
        return "BAJA";
    };

    const operationalRowsPrepared = useMemo(() => {
        const rows = (operationalComparison?.rows || []).map((row) => {
            const tag = getOperationalTag(row);
            const priority = getOperationalPriority(row, tag);
            const criticalScore =
                Number(row.required_production || 0) +
                (tag === "URGENTE_PRODUCIR" ? 1000000 : 0) +
                (tag === "RIESGO_QUIEBRE" ? 500000 : 0);
            return {
                ...row,
                operationalTag: tag,
                priority,
                criticalScore,
                line: getLineFromSku(row.sku),
            };
        });

        let filtered = rows;
        const query = operationalSearch.trim().toLowerCase();
        if (query) {
            filtered = filtered.filter((row) =>
                `${row.sku || ""} ${row.name || ""}`.toLowerCase().includes(query),
            );
        }
        if (operationalLineFilter !== "all") {
            filtered = filtered.filter((row) => row.line === operationalLineFilter);
        }
        if (operationalTagFilter !== "all") {
            filtered = filtered.filter((row) => row.operationalTag === operationalTagFilter);
        }
        if (operationalPriorityFilter !== "all") {
            filtered = filtered.filter((row) => row.priority === operationalPriorityFilter);
        }
        filtered = [...filtered].sort((a, b) => b.criticalScore - a.criticalScore);
        if (operationalTopLimit !== "all") {
            const n = Number(operationalTopLimit);
            if (!Number.isNaN(n) && n > 0) filtered = filtered.slice(0, n);
        }
        return filtered;
    }, [
        operationalComparison?.rows,
        operationalSearch,
        operationalLineFilter,
        operationalTagFilter,
        operationalPriorityFilter,
        operationalTopLimit,
    ]);

    const operationalLineOptions = useMemo(() => {
        const source = operationalComparison?.rows || [];
        const lines = Array.from(
            new Set(source.map((row) => getLineFromSku(row.sku)).filter(Boolean)),
        ).sort((a, b) => a.localeCompare(b));
        return lines;
    }, [operationalComparison?.rows]);

    const getTagClass = (tag) => {
        const styles = {
            CAIDA_DEMANDA: "bg-red-100 text-red-700",
            ALZA_DEMANDA: "bg-green-100 text-green-700",
            ESTABLE: "bg-slate-100 text-slate-700",
            SIN_DATA_HISTORICA: "bg-amber-100 text-amber-700",
            VOLATIL: "bg-fuchsia-100 text-fuchsia-700",
            URGENTE_PRODUCIR: "bg-red-100 text-red-700",
            RIESGO_QUIEBRE: "bg-orange-100 text-orange-700",
            SOBRE_STOCK: "bg-blue-100 text-blue-700",
            SIN_DATA_OPERATIVA: "bg-amber-100 text-amber-700",
            EN_RANGO: "bg-emerald-100 text-emerald-700",
            ALTA: "bg-red-100 text-red-700",
            MEDIA: "bg-amber-100 text-amber-700",
            BAJA: "bg-slate-100 text-slate-700",
        };
        return styles[tag] || "bg-slate-100 text-slate-700";
    };


    return (
        <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-6">
            <div className="max-w-7xl mx-auto">
                <div className="flex justify-between items-center mb-6">
                    <div className="flex items-center gap-3">
                        <TrendingUp className="w-8 h-8 text-blue-600" />
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900">Proyección de Ventas</h1>
                            <p className="text-gray-500">{selectedCompany?.name} · Unidades + Esencia</p>
                        </div>
                    </div>
                    <div className="flex gap-3">
                        <Select value={projectionView} onValueChange={setProjectionView}>
                            <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value="units">Por unidades (SKU)</SelectItem>
                                <SelectItem value="essence">Por esencia</SelectItem>
                            </SelectContent>
                        </Select>
                        <Select value={selectedYear} onValueChange={setSelectedYear}>
                            <SelectTrigger className="w-32">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                {Array.from({ length: 3 }, (_, i) => {
                                    const year = new Date().getFullYear() + i;
                                    return (
                                        <SelectItem key={year} value={year.toString()}>
                                            {year}
                                        </SelectItem>
                                    );
                                })}
                            </SelectContent>
                        </Select>
                    </div>
                </div>

                {projectionView === "units" ? (
                <>
                {/* Summary */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-sm text-gray-600">Productos Proyectados</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <p className="text-3xl font-bold text-blue-600">{projections.length}</p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-sm text-gray-600">Total Año {selectedYear}</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <p className="text-3xl font-bold text-green-600">
                                {summary.totalYear.toLocaleString('es-CL')}
                            </p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-sm text-gray-600">Promedio Mensual</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <p className="text-3xl font-bold text-purple-600">
                                {summary.monthlyAverage.toLocaleString('es-CL')}
                            </p>
                        </CardContent>
                    </Card>
                </div>

                {/* Projections Table */}
                <Card>
                    <CardHeader>
                        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                            <CardTitle>Proyecciones Mensuales por Producto</CardTitle>
                            <div className="flex flex-wrap items-center gap-2">
                                <Input
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    placeholder="Buscar por SKU o producto..."
                                    className="w-[260px]"
                                />
                                <Select value={String(pageSize)} onValueChange={(value) => setPageSize(Number(value))}>
                                    <SelectTrigger className="w-[150px]">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="25">25 por página</SelectItem>
                                        <SelectItem value="50">50 por página</SelectItem>
                                        <SelectItem value="100">100 por página</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                            <table className="w-full">
                                <thead className="bg-gray-50 sticky top-0">
                                    <tr>
                                        <th className="text-left p-2 text-sm font-semibold sticky left-0 bg-gray-50 z-10">SKU</th>
                                        <th className="text-left p-2 text-sm font-semibold">Producto</th>
                                        {months.map(m => (
                                            <th key={m.key} className="text-center p-2 text-sm font-semibold">{m.label}</th>
                                        ))}
                                        <th className="text-center p-2 text-sm font-semibold bg-blue-50">Total</th>
                                        <th className="text-center p-2 text-sm font-semibold sticky right-0 bg-gray-50">Acción</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {pagedProjections.map((projection) => (
                                        <tr key={projection.id} className="border-t hover:bg-gray-50">
                                            <td className="p-2 text-sm font-mono sticky left-0 bg-white">
                                                {projection.sku}
                                            </td>
                                            <td className="p-2 text-sm">{projection.product_name}</td>
                                            {months.map(m => (
                                                <td key={m.key} className="p-1">
                                                    <Input
                                                        type="number"
                                                        min="0"
                                                        value={getValue(projection, m.key)}
                                                        onChange={(e) => handleMonthChange(projection.id, m.key, e.target.value)}
                                                        className="w-16 text-center text-sm"
                                                    />
                                                </td>
                                            ))}
                                            <td className="p-2 text-center font-bold bg-blue-50">
                                                {getTotalYear(projection).toLocaleString('es-CL')}
                                            </td>
                                            <td className="p-2 text-center sticky right-0 bg-white">
                                                {editingProjections[projection.id] && (
                                                    <Button 
                                                        size="sm" 
                                                        onClick={() => saveProjection(projection)}
                                                        disabled={isSaving}
                                                    >
                                                        <Save className="w-4 h-4" />
                                                    </Button>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {filteredProjections.length > 0 && (
                            <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                                <p className="text-sm text-gray-500">
                                    Mostrando {pageStart + 1}-{Math.min(pageStart + pageSize, filteredProjections.length)} de {filteredProjections.length} registros
                                </p>
                                <div className="flex items-center gap-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => setPage((prev) => Math.max(1, prev - 1))}
                                        disabled={safePage <= 1}
                                    >
                                        Anterior
                                    </Button>
                                    <span className="text-sm text-gray-600">
                                        Página {safePage} de {totalPages}
                                    </span>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
                                        disabled={safePage >= totalPages}
                                    >
                                        Siguiente
                                    </Button>
                                </div>
                            </div>
                        )}

                        {projections.length === 0 && (
                            <div className="py-12 text-center">
                                <BarChart3 className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                                <p className="text-gray-500">No hay proyecciones para el año {selectedYear}</p>
                                <p className="text-sm text-gray-400 mt-2">
                                    Las proyecciones se generan automáticamente por proceso programado (cron/comando).
                                </p>
                            </div>
                        )}
                        {projections.length > 0 && filteredProjections.length === 0 && (
                            <div className="py-10 text-center">
                                <p className="text-gray-500">No hay resultados para la búsqueda ingresada.</p>
                            </div>
                        )}
                    </CardContent>
                </Card>

                {/* Guía visual de comparativas */}
                <div className="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <Card className="border-blue-200 bg-blue-50/60">
                        <CardContent className="pt-5">
                            <p className="text-xs font-semibold text-blue-700 uppercase tracking-wide">Comparativa histórica</p>
                            <p className="text-sm font-medium text-blue-900 mt-1">Proyección vs Venta Real (meses cerrados previos)</p>
                            <div className="text-xs text-blue-800 mt-2 space-y-1">
                                <p><span className="font-semibold">Objetivo:</span> validar si la proyección viene alineada con la demanda real.</p>
                                <p><span className="font-semibold">Regla principal (promedio 4 meses):</span> Alza demanda {">="} +10%, Caída demanda {"<="} -10%, Estable entre -10% y +10%.</p>
                                <p><span className="font-semibold">Regla secundaria:</span> Volátil si hay cambios bruscos entre meses.</p>
                                <p><span className="font-semibold">Top desvío:</span> Alza (solo positivos) o Baja (solo negativos).</p>
                            </div>
                        </CardContent>
                    </Card>
                    <Card className="border-indigo-200 bg-indigo-50/60">
                        <CardContent className="pt-5">
                            <p className="text-xs font-semibold text-indigo-700 uppercase tracking-wide">Comparativa operativa</p>
                            <p className="text-sm font-medium text-indigo-900 mt-1">Mes foco para decidir producción</p>
                            <div className="text-xs text-indigo-800 mt-2 space-y-1">
                                <p><span className="font-semibold">Objetivo:</span> priorizar qué SKU producir primero en el mes foco.</p>
                                <p><span className="font-semibold">Lectura base:</span> Proyección, venta, stock cierre, producido y requerido a producir.</p>
                                <p><span className="font-semibold">Prioridad:</span> Alta (riesgo de quiebre/urgencia), Media (ajuste), Baja (en rango).</p>
                                <p><span className="font-semibold">Filtros:</span> tag operativo, prioridad y Top críticos para enfocarse en lo urgente.</p>
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Comparativa Proyección vs Venta real */}
                <Card className="mt-6">
                    <CardHeader>
                        <div className="flex items-center justify-between flex-wrap gap-2 mb-2">
                            <CardTitle className="flex items-center gap-2">
                                <BarChart3 className="w-5 h-5 text-blue-600" />
                                Comparativa Proyección vs Venta Real
                            </CardTitle>
                            <div className="flex items-center gap-2">
                                <div className="h-10 px-3 rounded-md border bg-white text-sm flex items-center text-gray-700">
                                    Últimos 4 meses
                                </div>
                                <Input
                                    value={comparisonSearch}
                                    onChange={(e) => setComparisonSearch(e.target.value)}
                                    placeholder="Buscar SKU o producto..."
                                    className="w-56"
                                />
                                <Select value={comparisonLineFilter} onValueChange={setComparisonLineFilter}>
                                    <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Línea: todas</SelectItem>
                                        {comparisonLineOptions.map((line) => (
                                            <SelectItem key={line} value={line}>
                                                {line === "SIN_LINEA" ? "Sin línea" : line}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <Select value={comparisonTagFilter} onValueChange={setComparisonTagFilter}>
                                    <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Tendencia: todos</SelectItem>
                                        <SelectItem value="CAIDA_DEMANDA">Caída demanda</SelectItem>
                                        <SelectItem value="ALZA_DEMANDA">Alza demanda</SelectItem>
                                        <SelectItem value="ESTABLE">Estable</SelectItem>
                                        <SelectItem value="SIN_DATA_HISTORICA">Sin data histórica</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Select value={comparisonSecondaryTagFilter} onValueChange={setComparisonSecondaryTagFilter}>
                                    <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Comportamiento: todos</SelectItem>
                                        <SelectItem value="VOLATIL">Volátil</SelectItem>
                                        <SelectItem value="NO_VOLATIL">No volátil</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Select value={comparisonTopLimit} onValueChange={setComparisonTopLimit}>
                                    <SelectTrigger className="w-32"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Top: todos</SelectItem>
                                        <SelectItem value="10">Top 10</SelectItem>
                                        <SelectItem value="20">Top desvío 20</SelectItem>
                                        <SelectItem value="50">Top desvío 50</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Select value={comparisonTopMode} onValueChange={setComparisonTopMode}>
                                    <SelectTrigger className="w-36"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="UP">Top alza</SelectItem>
                                        <SelectItem value="DOWN">Top baja</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Button variant="outline" size="sm" onClick={loadComparison} disabled={comparisonLoading}>
                                    <RefreshCw className={`w-4 h-4 ${comparisonLoading ? "animate-spin" : ""}`} />
                                </Button>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent>
                        {comparisonLoading ? (
                            <p className="text-gray-500 text-sm">Cargando…</p>
                        ) : comparison?.rows?.length ? (
                            <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="text-left p-2 sticky left-0 bg-gray-50">Producto</th>
                                            {comparison.periods.map((p) => (
                                                <th key={`${p.year}-${p.month}`} className="text-center p-2" colSpan={3}>
                                                    {monthsLabel[p.month]} {p.year}
                                                </th>
                                            ))}
                                            <th className="text-center p-2 bg-gray-50" rowSpan={2}>Tendencia</th>
                                            <th className="text-center p-2 bg-gray-50" rowSpan={2}>Comportamiento</th>
                                        </tr>
                                        <tr className="bg-gray-100 text-[11px] text-gray-600">
                                            <th className="p-1 sticky left-0 bg-gray-100"></th>
                                            {comparison.periods.map((p) => (
                                                <React.Fragment key={`h-${p.year}-${p.month}`}>
                                                    <th className="text-right p-1">Proy.</th>
                                                    <th className="text-right p-1">Real</th>
                                                    <th className="text-right p-1">Δ</th>
                                                </React.Fragment>
                                            ))}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {comparisonRowsPrepared.length === 0 ? (
                                            <tr>
                                                <td colSpan={comparison.periods.length * 3 + 3} className="p-4 text-center text-gray-500">
                                                    No hay productos para los filtros seleccionados.
                                                </td>
                                            </tr>
                                        ) : comparisonRowsPrepared.map((row) => (
                                            <tr key={row.idproduct} className="border-t hover:bg-gray-50">
                                                <td className="p-2 sticky left-0 bg-white">
                                                    <div className="font-medium">{row.name}</div>
                                                    <div className="text-[11px] text-gray-500 font-mono">{row.sku}</div>
                                                </td>
                                                {row.cells.map((c) => {
                                                    const positive = c.variance > 0;
                                                    const negative = c.variance < 0;
                                                    const variancePctLabel = c.variance_pct != null ? ` (${c.variance_pct > 0 ? "+" : ""}${c.variance_pct}%)` : "";
                                                    return (
                                                        <React.Fragment key={`${row.idproduct}-${c.year}-${c.month}`}>
                                                            <td className="p-1 text-right text-gray-700">{c.projected.toLocaleString("es-CL")}</td>
                                                            <td className="p-1 text-right font-medium">{c.sold.toLocaleString("es-CL")}</td>
                                                            <td className={`p-1 text-right font-semibold ${positive ? "text-green-600" : ""} ${negative ? "text-red-600" : ""}`}>
                                                                <span className="inline-flex items-center gap-1">
                                                                    {positive ? <ArrowUpRight className="w-3 h-3" /> : null}
                                                                    {negative ? <ArrowDownRight className="w-3 h-3" /> : null}
                                                                    {(c.variance > 0 ? "+" : "") + c.variance.toLocaleString("es-CL")}
                                                                    <span className="text-[10px] text-gray-500">{variancePctLabel}</span>
                                                                </span>
                                                            </td>
                                                        </React.Fragment>
                                                    );
                                                })}
                                                <td className="p-2 text-center">
                                                    <span className={`inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium ${getTagClass(row.comparisonTag)}`}>
                                                        {row.comparisonTag}
                                                    </span>
                                                </td>
                                                <td className="p-2 text-center">
                                                    {row.comparisonSecondaryTag ? (
                                                        <span className={`inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium ${getTagClass(row.comparisonSecondaryTag)}`}>
                                                            {row.comparisonSecondaryTag}
                                                        </span>
                                                    ) : (
                                                        <span className="text-xs text-gray-400">-</span>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : projections.length > 0 ? (
                            <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="text-left p-2 sticky left-0 bg-gray-50">Producto</th>
                                            {fallbackComparisonPeriods.map((p) => (
                                                <th key={`${p.year}-${p.month}`} className="text-center p-2" colSpan={3}>
                                                    {monthsLabel[p.month]} {p.year}
                                                </th>
                                            ))}
                                            <th className="text-center p-2 bg-gray-50" rowSpan={2}>Tendencia</th>
                                            <th className="text-center p-2 bg-gray-50" rowSpan={2}>Comportamiento</th>
                                        </tr>
                                        <tr className="bg-gray-100 text-[11px] text-gray-600">
                                            <th className="p-1 sticky left-0 bg-gray-100"></th>
                                            {fallbackComparisonPeriods.map((p) => (
                                                <React.Fragment key={`fallback-h-${p.year}-${p.month}`}>
                                                    <th className="text-right p-1">Proy.</th>
                                                    <th className="text-right p-1">Real</th>
                                                    <th className="text-right p-1">Δ</th>
                                                </React.Fragment>
                                            ))}
                                        </tr>
                                    </thead>
                                </table>
                                <p className="text-xs text-gray-500 mt-3">
                                    Se muestran solo columnas. "Comportamiento: Volátil" aparece cuando hay filas con datos.
                                </p>
                            </div>
                        ) : (
                            <p className="text-gray-500 text-sm py-6 text-center">Aún no hay datos suficientes para comparar.</p>
                        )}
                    </CardContent>
                </Card>

                {/* Comparativa operativa mensual */}
                <Card className="mt-6">
                    <CardHeader>
                        <div className="flex items-center justify-between flex-wrap gap-2 mb-2">
                            <CardTitle className="flex items-center gap-2">
                                <BarChart3 className="w-5 h-5 text-indigo-600" />
                                Comparativa operativa mensual
                            </CardTitle>
                            <div className="flex items-center gap-2">
                                <div className="h-10 px-3 rounded-md border bg-white text-sm flex items-center text-gray-700 w-32">
                                    {monthsLabel[operationalMonth]}
                                </div>
                                <Input
                                    value={operationalSearch}
                                    onChange={(e) => setOperationalSearch(e.target.value)}
                                    placeholder="Buscar SKU o producto..."
                                    className="w-56"
                                />
                                <Select value={operationalLineFilter} onValueChange={setOperationalLineFilter}>
                                    <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Línea: todas</SelectItem>
                                        {operationalLineOptions.map((line) => (
                                            <SelectItem key={line} value={line}>
                                                {line === "SIN_LINEA" ? "Sin línea" : line}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <Select value={operationalTagFilter} onValueChange={setOperationalTagFilter}>
                                    <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Tag: todos</SelectItem>
                                        <SelectItem value="URGENTE_PRODUCIR">Urgente producir</SelectItem>
                                        <SelectItem value="RIESGO_QUIEBRE">Riesgo quiebre</SelectItem>
                                        <SelectItem value="SOBRE_STOCK">Sobre stock</SelectItem>
                                        <SelectItem value="SIN_DATA_OPERATIVA">Sin data operativa</SelectItem>
                                        <SelectItem value="EN_RANGO">En rango</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Select value={operationalPriorityFilter} onValueChange={setOperationalPriorityFilter}>
                                    <SelectTrigger className="w-32"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">Prioridad: todas</SelectItem>
                                        <SelectItem value="ALTA">Alta</SelectItem>
                                        <SelectItem value="MEDIA">Media</SelectItem>
                                        <SelectItem value="BAJA">Baja</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Select value={operationalTopLimit} onValueChange={setOperationalTopLimit}>
                                    <SelectTrigger className="w-32"><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="20">Top 20</SelectItem>
                                        <SelectItem value="50">Top 50</SelectItem>
                                        <SelectItem value="100">Top 100</SelectItem>
                                        <SelectItem value="all">Todos</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Button variant="outline" size="sm" onClick={loadOperationalComparison} disabled={operationalLoading}>
                                    <RefreshCw className={`w-4 h-4 ${operationalLoading ? "animate-spin" : ""}`} />
                                </Button>
                            </div>
                        </div>
                        <div className="flex flex-wrap items-center gap-2 text-xs">
                            <span className="inline-flex items-center rounded-full bg-indigo-100 text-indigo-800 px-2 py-1 font-medium">
                                Mes foco {monthsLabel[operationalMonth]} {selectedYear}
                            </span>
                            <span className="inline-flex items-center rounded-full bg-slate-100 text-slate-700 px-2 py-1">
                                Decisión: priorizar producción
                            </span>
                        </div>
                    </CardHeader>
                    <CardContent>
                        {operationalLoading ? (
                            <p className="text-gray-500 text-sm">Cargando…</p>
                        ) : operationalComparison?.rows?.length ? (
                            <div className="overflow-x-auto">
                                <div className="grid grid-cols-1 md:grid-cols-5 gap-3 mb-4">
                                    <div className="rounded border p-2">
                                        <div className="text-xs text-muted-foreground">Proyección total</div>
                                        <div className="text-lg font-bold">{Number(operationalComparison.summary?.projected_total || 0).toLocaleString("es-CL")}</div>
                                    </div>
                                    <div className="rounded border p-2">
                                        <div className="text-xs text-muted-foreground">Vendido total</div>
                                        <div className="text-lg font-bold">{Number(operationalComparison.summary?.sold_total || 0).toLocaleString("es-CL")}</div>
                                    </div>
                                    <div className="rounded border p-2">
                                        <div className="text-xs text-muted-foreground">Stock cierre total</div>
                                        <div className="text-lg font-bold">{Number(operationalComparison.summary?.closing_stock_total || 0).toLocaleString("es-CL")}</div>
                                    </div>
                                    <div className="rounded border p-2">
                                        <div className="text-xs text-muted-foreground">Producido total</div>
                                        <div className="text-lg font-bold">{Number(operationalComparison.summary?.produced_total || 0).toLocaleString("es-CL")}</div>
                                    </div>
                                    <div className="rounded border p-2">
                                        <div className="text-xs text-muted-foreground">Producción requerida</div>
                                        <div className="text-lg font-bold text-amber-700">{Number(operationalComparison.summary?.required_production_total || 0).toLocaleString("es-CL")}</div>
                                    </div>
                                </div>
                                <table className="w-full text-sm">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="text-left p-2">SKU</th>
                                            <th className="text-left p-2">Producto</th>
                                            <th className="text-right p-2">Proyección</th>
                                            <th className="text-right p-2">Venta real</th>
                                            <th className="text-right p-2">Stock cierre</th>
                                            <th className="text-right p-2">Producido</th>
                                            <th className="text-right p-2">Req. producir</th>
                                            <th className="text-center p-2">Prioridad</th>
                                            <th className="text-center p-2">Tag</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {operationalRowsPrepared.length === 0 ? (
                                            <tr>
                                                <td colSpan={9} className="p-4 text-center text-gray-500">
                                                    No hay productos para los filtros seleccionados.
                                                </td>
                                            </tr>
                                        ) : operationalRowsPrepared.map((row) => (
                                            <tr key={row.idproduct} className="border-t hover:bg-gray-50">
                                                <td className="p-2 font-mono">{row.sku}</td>
                                                <td className="p-2">{row.name}</td>
                                                <td className="p-2 text-right">{Number(row.projected || 0).toLocaleString("es-CL")}</td>
                                                <td className="p-2 text-right">{Number(row.sold || 0).toLocaleString("es-CL")}</td>
                                                <td className="p-2 text-right">{Number(row.closing_stock || 0).toLocaleString("es-CL")}</td>
                                                <td className="p-2 text-right">{Number(row.produced || 0).toLocaleString("es-CL")}</td>
                                                <td className="p-2 text-right font-semibold text-amber-700">{Number(row.required_production || 0).toLocaleString("es-CL")}</td>
                                                <td className="p-2 text-center">
                                                    <span className={`inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium ${getTagClass(row.priority)}`}>
                                                        {row.priority}
                                                    </span>
                                                </td>
                                                <td className="p-2 text-center">
                                                    <span className={`inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium ${getTagClass(row.operationalTag)}`}>
                                                        {row.operationalTag}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : projections.length > 0 ? (
                            <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="text-left p-2">SKU</th>
                                            <th className="text-left p-2">Producto</th>
                                            <th className="text-right p-2">Proyección</th>
                                            <th className="text-right p-2">Venta real</th>
                                            <th className="text-right p-2">Stock cierre</th>
                                            <th className="text-right p-2">Producido</th>
                                            <th className="text-right p-2">Req. producir</th>
                                            <th className="text-center p-2">Prioridad</th>
                                            <th className="text-center p-2">Tag</th>
                                        </tr>
                                    </thead>
                                </table>
                                <p className="text-xs text-gray-500 mt-3">
                                    Se muestran solo columnas para {monthsLabel[operationalMonth]} {selectedYear}. Falta cargar datos operativos del período.
                                </p>
                            </div>
                        ) : (
                            <p className="text-gray-500 text-sm py-6 text-center">
                                Sin datos operativos para {monthsLabel[operationalMonth]} {selectedYear}.
                            </p>
                        )}
                    </CardContent>
                </Card>
                </>
                ) : null}

                {projectionView === "essence" ? (
                    <Card className="mt-6">
                        <CardHeader className="flex flex-row items-center justify-between">
                            <CardTitle>Consumo proyectado por esencia</CardTitle>
                            <Button variant="outline" size="sm" onClick={loadEssenceProjection} disabled={essenceLoading}>
                                <RefreshCw className={`w-4 h-4 ${essenceLoading ? "animate-spin" : ""}`} />
                            </Button>
                        </CardHeader>
                        <CardContent>
                            {essenceLoading ? (
                                <p className="text-sm text-gray-500">Calculando…</p>
                            ) : essenceProjection?.rows?.length ? (
                                <div className="overflow-x-auto">
                                    <table className="w-full text-sm">
                                        <thead className="bg-gray-50">
                                            <tr>
                                                <th className="text-left p-2">Esencia (SKU)</th>
                                                <th className="text-left p-2">Nombre</th>
                                                <th className="text-right p-2">Proy. esencia</th>
                                                <th className="text-right p-2">Stock físico</th>
                                                <th className="text-right p-2">Reservado</th>
                                                <th className="text-right p-2">Libre</th>
                                                <th className="text-right p-2">Déficit</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {essenceProjection.rows.map((row) => (
                                                <tr key={row.idessence_product} className="border-t hover:bg-gray-50">
                                                    <td className="p-2 font-mono">{row.essence_sku}</td>
                                                    <td className="p-2">{row.essence_name}</td>
                                                    <td className="p-2 text-right">{Number(row.projected_ml || 0).toLocaleString("es-CL")}</td>
                                                    <td className="p-2 text-right">{Number(row.stock_physical || 0).toLocaleString("es-CL")}</td>
                                                    <td className="p-2 text-right">{Number(row.stock_reserved || 0).toLocaleString("es-CL")}</td>
                                                    <td className="p-2 text-right">{Number(row.stock_free || 0).toLocaleString("es-CL")}</td>
                                                    <td className="p-2 text-right font-semibold text-amber-700">{Number(row.deficit_ml || 0).toLocaleString("es-CL")}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                    <p className="text-xs text-gray-500 mt-3">
                                        Agrupación por material esencia (SKU 3-E-*). Reservado v2/v3: PR capturada, SR pendiente y OP en curso. Generar PR planificada por esencia desde Solicitudes de producción.
                                    </p>
                                </div>
                            ) : (
                                <p className="text-sm text-gray-500 py-6 text-center">
                                    Sin datos de esencia para {selectedYear}. Verifique fórmulas activas y ml en productos.
                                </p>
                            )}
                        </CardContent>
                    </Card>
                ) : null}
            </div>
        </div>
    );
}