"use client";

import React, { useMemo, useState, useEffect } from "react";
import { useGridStore } from "@/store/use-grid-store";
import { BarChart, Bar, XAxis, YAxis, ResponsiveContainer, ReferenceLine, Cell, Tooltip, Tooltip as RechartsTooltip } from "recharts";
import { X, AlertTriangle, ShieldCheck, Eye, EyeOff, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";

interface InsightPanelProps {
  colName: string;
  onClose: () => void;
}

export function InsightPanel({ colName, onClose }: InsightPanelProps) {
  const { data, detectedOutliers, multivariateOutliers, excludeBatch, toggleRowExclusion, excludedRows, setActiveInsightColumn } = useGridStore();

  // Handle both column-specific and global multivariate outliers
  const isGlobalView = colName === '__GLOBAL__';
  const outliers = isGlobalView ? multivariateOutliers : (detectedOutliers[colName] || []);

  const [showDetails, setShowDetails] = useState(false);
  const [rowsToExclude, setRowsToExclude] = useState<number[]>([]);
  const [hasExcluded, setHasExcluded] = useState(false);

  // Set active insight column when panel opens, clear when closes
  useEffect(() => {
    // Set active column: either specific column or '__GLOBAL__' for multivariate view
    setActiveInsightColumn(colName);
    return () => {
      setActiveInsightColumn(null);
    };
  }, [colName, setActiveInsightColumn]);

  // Get full row data for each outlier
  const outliersWithData = useMemo(() => {
    return outliers.map((o) => ({
      ...o,
      rowData: data[o.index] || {},
      isExcluded: excludedRows.has(o.index)
    }));
  }, [outliers, data, excludedRows]);

  // Only non-excluded outliers can be selected
  const availableOutliers = useMemo(() => {
    return outliersWithData.filter(o => !o.isExcluded);
  }, [outliersWithData]);

  // Statistics about what will be excluded
  const excludeStats = useMemo(() => {
    const allOutlierIndices = new Set(
      Object.values(detectedOutliers).flat().map(o => o.index)
    );
    const currentColIndices = new Set(outliers.map(o => o.index));

    return {
      totalInColumn: outliers.length,
      alreadyExcluded: outliers.filter(o => excludedRows.has(o.index)).length,
      available: availableOutliers.length,
      willBeNewlyExcluded: rowsToExclude.filter(i => !excludedRows.has(i)).length,
      affectedColumns: Object.keys(detectedOutliers).filter(col =>
        detectedOutliers[col].some(o => rowsToExclude.includes(o.index))
      ).length
    };
  }, [detectedOutliers, rowsToExclude, outliers, excludedRows, availableOutliers]);

  const chartData = useMemo(() => {
    const values = data.map(r => Number(r[colName])).filter(v => !isNaN(v));
    if (values.length === 0) return [];

    const min = Math.min(...values);
    const max = Math.max(...values);
    const step = (max - min) / 10;

    const bins = Array.from({ length: 10 }, (_, i) => ({
      range: `${(min + i * step).toFixed(1)}`,
      count: 0,
      isOutlier: false
    }));

    values.forEach(v => {
      const binIdx = Math.min(Math.floor((v - min) / step), 9);
      bins[binIdx].count++;
    });

    return bins;
  }, [data, colName]);

  const handleToggleRow = (rowIndex: number) => {
    toggleRowExclusion(rowIndex);
    setHasExcluded(true);
  };

  const handleExcludeSelected = () => {
    if (rowsToExclude.length > 0) {
      // Only exclude rows that are not already excluded (defensive programming)
      const newExclusions = rowsToExclude.filter(idx => !excludedRows.has(idx));
      if (newExclusions.length > 0) {
        excludeBatch(newExclusions);
      }
      setHasExcluded(true);
      setRowsToExclude([]);
    }
  };

  const toggleAll = () => {
    // Toggle selection for available (non-excluded) outliers only
    const availableIndices = availableOutliers.map(o => o.index);
    const allAvailableSelected = availableIndices.length > 0 &&
      availableIndices.every(idx => rowsToExclude.includes(idx));

    if (allAvailableSelected) {
      // Deselect all available outliers
      setRowsToExclude(rowsToExclude.filter(idx => !availableIndices.includes(idx)));
    } else {
      // Select all available outliers (keep already selected ones)
      setRowsToExclude([...new Set([...rowsToExclude, ...availableIndices])]);
    }
  };

  const allSelected = availableOutliers.length > 0 &&
    availableOutliers.every(o => rowsToExclude.includes(o.index));

  return (
    <div className="fixed right-0 top-0 h-screen w-[450px] bg-white border-l border-slate-200 shadow-2xl z-50 flex flex-col animate-in slide-in-from-right duration-300">
      <header className={`p-4 bg-gradient-to-r text-white flex items-center justify-between ${
        isGlobalView ? "from-purple-600 to-purple-700" : "from-rose-600 to-rose-700"
      }`}>
        <div className="flex items-center gap-2">
          <AlertTriangle className="w-5 h-5" />
          <div>
            <h3 className="font-bold text-sm">
              {isGlobalView ? "Anomalies Multivariées" : `Anomalies : ${colName}`}
            </h3>
            <p className="text-[10px] opacity-90">
              {isGlobalView
                ? `${outliers.length} anomalie${outliers.length > 1 ? 's' : ''} globale${outliers.length > 1 ? 's' : ''} détectée${outliers.length > 1 ? 's' : ''}`
                : `${outliers.length} valeur${outliers.length > 1 ? 's' : ''} détectée${outliers.length > 1 ? 's' : ''}`
              }
            </p>
          </div>
        </div>
        <div className="flex items-center gap-1">
          <button onClick={onClose} className="hover:bg-white/20 p-1 rounded transition-colors">
            <X className="w-5 h-5" />
          </button>
        </div>
      </header>

      <div className="flex-1 overflow-y-auto p-6 space-y-6">
        {/* Warning Banner */}
        <div className={`border p-3 rounded-lg ${
          isGlobalView
            ? "bg-purple-50 border-purple-200"
            : "bg-amber-50 border-amber-200"
        }`}>
          <p className={`text-[10px] leading-relaxed ${
            isGlobalView
              ? "text-purple-800"
              : "text-amber-800"
          }`}>
            <strong>
              {isGlobalView
                ? "🔍 Anomalies Globales :"
                : "⚠️ Important :"
              }
            </strong>{" "}
            {isGlobalView
              ? "Ces anomalies sont détectées par Isolation Forest en analysant les COMBINAISONS de valeurs across toutes les colonnes numériques. Une ligne peut sembler normale individuellement mais être anormale dans le contexte multivarié."
              : "Les lignes que vous excluez seront masquées dans toutes les colonnes pour garantir la cohérence des données."
            }
          </p>
        </div>

        {/* Summary Stats */}
        <section className="space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-slate-50 p-3 rounded-lg border border-slate-100">
              <p className="text-[10px] text-slate-400 uppercase tracking-widest">Total anomalies</p>
              <p className="text-lg font-bold text-slate-800">{excludeStats.totalInColumn}</p>
            </div>
            <div className="bg-slate-50 p-3 rounded-lg border border-slate-100">
              <p className="text-[10px] text-slate-400 uppercase tracking-widest">Déjà exclues</p>
              <p className="text-lg font-bold text-rose-600">{excludeStats.alreadyExcluded}</p>
            </div>
          </div>
        </section>

        {/* Histogram */}
        <section className="space-y-3">
          <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Distribution des données</p>
          <div className="h-40 w-full border border-slate-100 rounded-xl p-2 bg-slate-50">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={chartData}>
                <XAxis dataKey="range" fontSize={10} hide />
                <Bar dataKey="count" fill="#818cf8" radius={[2, 2, 0, 0]} />
                <RechartsTooltip
                  content={({ active, payload }) => {
                    if (active && payload && payload.length) {
                      return (
                        <div className="bg-white p-2 border border-slate-200 rounded shadow-lg">
                          <p className="text-xs font-semibold">Valeurs: {payload[0].payload.range}</p>
                          <p className="text-xs">Count: {payload[0].payload.count}</p>
                        </div>
                      );
                    }
                    return null;
                  }}
                />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </section>

        {/* Select / Deselect All */}
        <section className="flex items-center justify-between p-3 bg-slate-50 rounded-lg border border-slate-100">
          <span className="text-xs font-medium text-slate-700">
            {rowsToExclude.length} / {availableOutliers.length} sélectionnée{rowsToExclude.length > 1 ? 's' : ''}
            {excludeStats.alreadyExcluded > 0 && (
              <span className="text-slate-400 ml-1">
                ({excludeStats.alreadyExcluded} déjà exclue{excludeStats.alreadyExcluded > 1 ? 's' : ''})
              </span>
            )}
          </span>
          <button
            onClick={toggleAll}
            disabled={availableOutliers.length === 0}
            className={cn(
              "text-xs font-medium",
              availableOutliers.length === 0
                ? "text-slate-400 cursor-not-allowed"
                : "text-indigo-600 hover:text-indigo-800"
            )}
          >
            {allSelected ? "Tout désélectionner" : "Tout sélectionner"}
          </button>
        </section>

        {/* List of outliers with row data */}
        <section className="space-y-3">
          <div className="flex items-center justify-between">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Détails des anomalies</p>
            <button
              onClick={() => setShowDetails(!showDetails)}
              className="text-xs text-indigo-600 hover:text-indigo-800 font-medium flex items-center gap-1"
            >
              {showDetails ? "Masquer" : "Afficher"} les données
              {showDetails ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
            </button>
          </div>

          <div className="space-y-2 max-h-[400px] overflow-y-auto">
            {outliersWithData.length === 0 ? (
              <div className="text-center py-8 text-slate-400 text-sm">
                Aucune anomalie détectée dans cette colonne.
              </div>
            ) : (
              outliersWithData.map((outlier, i) => {
                const isSelected = rowsToExclude.includes(outlier.index);
                const canSelect = !outlier.isExcluded;

                return (
                  <div
                    key={i}
                    className={cn(
                      "border rounded-lg p-3 transition-all",
                      canSelect ? "cursor-pointer hover:shadow-md" : "cursor-not-allowed opacity-60",
                      isSelected
                        ? "bg-rose-50 border-rose-300 ring-2 ring-rose-200"
                        : outlier.isExcluded
                          ? "bg-slate-100 border-slate-200"
                          : "bg-white border-slate-200"
                    )}
                    onClick={() => {
                      if (!canSelect) return; // Don't allow selecting already excluded rows

                      if (rowsToExclude.includes(outlier.index)) {
                        setRowsToExclude(rowsToExclude.filter(idx => idx !== outlier.index));
                      } else {
                        setRowsToExclude([...rowsToExclude, outlier.index]);
                      }
                    }}
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          disabled={!canSelect}
                          onChange={() => {}}
                          className={cn(
                            "rounded",
                            canSelect
                              ? "border-slate-300 text-rose-600 focus:ring-rose-500"
                              : "border-slate-200 text-slate-400 cursor-not-allowed"
                          )}
                          onClick={(e) => e.stopPropagation()}
                        />
                        <span className="text-xs font-bold text-slate-700">
                          Ligne {outlier.index + 1}
                        </span>
                        {outlier.isExcluded && (
                          <span className="px-2 py-0.5 bg-slate-200 text-slate-500 text-[9px] rounded font-medium">
                            Déjà exclue
                          </span>
                        )}
                      </div>
                      <div className="flex items-center gap-1">
                        <span className={cn(
                          "text-[10px] font-mono px-2 py-0.5 rounded",
                          outlier.isExcluded
                            ? "bg-slate-200 text-slate-500"
                            : isGlobalView
                              ? "bg-purple-100 text-purple-700"
                              : "bg-rose-100 text-rose-700"
                        )}>
                          {!isGlobalView && outlier.rowData[colName] !== undefined
                            ? outlier.rowData[colName].toFixed(4)
                            : isGlobalView
                              ? "Multivarié"
                              : 'N/A'}
                        </span>
                      </div>
                    </div>

                    <p className="text-[10px] text-slate-500 ml-6 mb-2">
                      {outlier.reasons[0]}
                    </p>

                    {showDetails && (
                      <div className="ml-6 p-2 bg-slate-50 rounded border border-slate-100">
                        <p className="text-[9px] text-slate-400 uppercase tracking-wider mb-1">Données complètes de la ligne</p>
                        <div className="grid grid-cols-2 gap-2 text-[10px]">
                          {Object.entries(outlier.rowData).slice(0, 6).map(([key, val]) => (
                            <div key={key} className="truncate" title={String(val)}>
                              <span className="text-slate-400">{key}:</span>
                              <span className="text-slate-700 font-mono ml-1">
                                {typeof val === 'number' ? val.toFixed(2) : String(val)}
                              </span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })
            )}
          </div>
        </section>

        {/* Selection Summary */}
        {rowsToExclude.length > 0 && (
          <section className={`border p-4 rounded-xl space-y-2 ${
            isGlobalView
              ? "bg-purple-50 border-purple-200"
              : "bg-indigo-50 border-indigo-200"
          }`}>
            <p className={`text-xs font-bold ${
              isGlobalView
                ? "text-purple-900"
                : "text-indigo-900"
            }`}>
              📋 {excludeStats.willBeNewlyExcluded} nouvelle{excludeStats.willBeNewlyExcluded > 1 ? 's' : ''} ligne{excludeStats.willBeNewlyExcluded > 1 ? 's' : ''} sera{excludeStats.willBeNewlyExcluded > 1 ? 'ont' : ''} exclue{excludeStats.willBeNewlyExcluded > 1 ? 's' : ''}
            </p>
            <p className={`text-[10px] ${
              isGlobalView
                ? "text-purple-700"
                : "text-indigo-700"
            }`}>
              Ces lignes seront masquées dans <strong>toutes</strong> les colonnes.
            </p>
            {!isGlobalView && excludeStats.affectedColumns > 1 && (
              <p className="text-[10px] text-amber-700">
                ⚠️ Affecte aussi {excludeStats.affectedColumns - 1} autre{excludeStats.affectedColumns > 2 ? 's' : ''} colonne{excludeStats.affectedColumns > 2 ? 's' : ''} avec des anomalies.
              </p>
            )}
          </section>
        )}
      </div>

      <footer className="p-6 border-t border-slate-100 bg-slate-50/50 space-y-3">
        {rowsToExclude.length > 0 && (
          <div className={`flex items-center gap-2 text-xs font-medium p-2 rounded border ${
            isGlobalView
              ? "text-purple-600 bg-purple-50 border-purple-100"
              : "text-emerald-600 bg-emerald-50 border-emerald-100"
          }`}>
            <ShieldCheck className="w-4 h-4" />
            <span>
              {isGlobalView
                ? "L'exclusion des anomalies multivariées améliorera la cohérence globale des données."
                : "L'exclusion améliorera la qualité de vos analyses."
              }
            </span>
          </div>
        )}

        <div className="flex gap-2">
          <button
            onClick={handleExcludeSelected}
            disabled={excludeStats.willBeNewlyExcluded === 0}
            className={cn(
              "flex-1 py-3 rounded-xl text-sm font-bold shadow-lg transition-all",
              excludeStats.willBeNewlyExcluded === 0
                ? "bg-slate-200 text-slate-400 cursor-not-allowed"
                : isGlobalView
                  ? "bg-purple-600 hover:bg-purple-700 text-white shadow-purple-100"
                  : "bg-rose-600 hover:bg-rose-700 text-white shadow-rose-100"
            )}
          >
            Exclure ({excludeStats.willBeNewlyExcluded})
          </button>

          {rowsToExclude.length > 0 && (
            <button
              onClick={() => setRowsToExclude([])}
              className="px-4 py-3 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded-xl text-sm font-bold transition-all"
            >
              Annuler
            </button>
          )}
        </div>
      </footer>
    </div>
  );
}
