"use client";

import React, { useMemo, useState, useEffect, useRef } from "react";
import { useGridStore } from "@/store/use-grid-store";
import {
  ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  ReferenceLine, Legend, ComposedChart, Line
} from "recharts";
import { Activity, Percent, Database, TrendingUp, CheckCircle2, XCircle, Info, Copy, Check } from "lucide-react";
import { cn } from "@/lib/utils";
import katex from "katex";

// Custom tooltip with 2 decimal precision
const CustomTooltip = ({ active, payload, label }: any) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white p-3 border border-slate-200 rounded-lg shadow-lg">
        <p className="text-xs font-semibold text-slate-700 mb-2">{`X: ${label?.toFixed(2)}`}</p>
        {payload.map((entry: any, index: number) => (
          <p key={index} className="text-[10px]" style={{ color: entry.color }}>
            {`${entry.name}: ${typeof entry.value === 'number' ? entry.value.toFixed(2) : entry.value}`}
          </p>
        ))}
      </div>
    );
  }
  return null;
};

// LaTeX Renderer Component using KaTeX
function LatexRenderer({ latex, displayMode = true }: { latex: string; displayMode?: boolean }) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (containerRef.current && latex) {
      try {
        katex.render(latex, containerRef.current, {
          displayMode,
          throwOnError: false,
          output: 'html',
          trust: true,
        });
      } catch (error) {
        console.error('KaTeX render error:', error);
        if (containerRef.current) {
          containerRef.current.textContent = latex;
        }
      }
    }
  }, [latex, displayMode]);

  return <div ref={containerRef} className="overflow-x-auto" />;
}

// Helper component for copy button
function CopyButton({ text, label }: { text: string; label: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <button
      onClick={handleCopy}
      className="flex items-center gap-2 px-3 py-2 text-xs font-semibold text-slate-600 bg-slate-50 hover:bg-slate-100 rounded-lg border border-slate-200 transition-colors"
    >
      {copied ? <Check className="w-4 h-4 text-emerald-500" /> : <Copy className="w-4 h-4" />}
      {copied ? "Copié!" : label}
    </button>
  );
}

export function AnalysisResults() {
  const { analysisResults, modelType, selectedFeatures } = useGridStore();
  const [selectedPartialFeature, setSelectedPartialFeature] = useState<string>("");

  const { r_squared, adj_r_squared, coefficients, sample_size, fit_plot, fit_plots_by_feature, partial_regression_plots, diagnostic_plot, equations } = (analysisResults || {}) as any;
  const primaryFeature = selectedFeatures[0] || "X";

  // Initialize selected partial feature on first load
  const partialFeatures = useMemo(() => {
    return partial_regression_plots ? Object.keys(partial_regression_plots) : [];
  }, [partial_regression_plots]);

  // Auto-select first feature if none selected
  React.useEffect(() => {
    if (partialFeatures.length > 0 && !selectedPartialFeature) {
      setSelectedPartialFeature(partialFeatures[0]);
    }
  }, [partialFeatures, selectedPartialFeature]);

  if (!analysisResults) return (
    <div className="flex-1 flex flex-col items-center justify-center text-slate-400 gap-4">
      <TrendingUp className="w-12 h-12 opacity-20" />
      <p>Lancez une régression pour voir les résultats ici.</p>
    </div>
  );

  // Check if multivariate regression
  const isMultivariate = selectedFeatures.length > 1;

  // Get equations from backend or generate fallback
  const pythonEq = equations?.python || "";
  const excelEq = equations?.excel || "";
  const latexEqRaw = equations?.latex || "";

  // Data preparation for the Parity Plot (Real vs Pred)
  // We construct this from fit_plot data
  const parityData = fit_plot ? fit_plot.map((d: any) => ({
    real: d.real,
    pred: d.pred
  })) : [];

  // Calculate domains for Parity Plot to ensure square aspect ratio logic
  const allParityValues = parityData.flatMap((d: any) => [d.real, d.pred]);
  const minParity = Math.min(...allParityValues);
  const maxParity = Math.max(...allParityValues);
  const padding = (maxParity - minParity) * 0.05;
  const parityDomain = [minParity - padding, maxParity + padding];

  // Prepare fit plots for rendering (use multi-feature plots if available)
  const fitPlotsToRender = fit_plots_by_feature && Object.keys(fit_plots_by_feature).length > 0
    ? Object.entries(fit_plots_by_feature).map(([featureName, plotData]) => ({
        featureName,
        plotData: plotData as any[]
      }))
    : [{ featureName: primaryFeature, plotData: fit_plot || [] }];

  return (
    <div className="flex-1 overflow-y-auto space-y-8 p-4 pb-20">
      {/* 1. Metrics Overview */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">R-Squared</p>
            <Activity className="w-4 h-4 text-indigo-500" />
          </div>
          <p className="text-2xl font-bold text-slate-900">{Number(r_squared).toFixed(4)}</p>
          <p className="text-[10px] text-slate-500 mt-1">Précision (1.0 = Parfait)</p>
        </div>
        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Adj. R-Squared</p>
            <Percent className="w-4 h-4 text-indigo-500" />
          </div>
          <p className="text-2xl font-bold text-slate-900">{adj_r_squared ? Number(adj_r_squared).toFixed(4) : "N/A"}</p>
        </div>
        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Échantillon</p>
            <Database className="w-4 h-4 text-indigo-500" />
          </div>
          <p className="text-2xl font-bold text-slate-900">{sample_size}</p>
        </div>
        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Modèle</p>
            <CheckCircle2 className="w-4 h-4 text-emerald-500" />
          </div>
          <p className="text-lg font-bold text-slate-900 uppercase truncate" title={modelType}>{modelType}</p>
        </div>
      </div>

      {/* Equation Display and Copy Section */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        <header className="p-4 border-b border-slate-100 bg-slate-50/50">
          <h3 className="text-xs font-bold text-slate-500 uppercase tracking-widest">Équation du Modèle</h3>
        </header>
        <div className="p-6 space-y-6">
          {/* LaTeX Display */}
          <div className="bg-slate-50 rounded-xl p-6 border border-slate-200">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-3">Format Mathématique</p>
            <div className="text-center py-4">
              <LatexRenderer latex={latexEqRaw || "\text{Chargement...}"} />
            </div>
          </div>

          {/* Copy Buttons */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Python Format */}
            <div className="space-y-3">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Python / Code</p>
              <div className="bg-slate-900 rounded-lg p-4 font-mono text-xs text-emerald-400 break-all">
                {pythonEq}
              </div>
              <CopyButton text={pythonEq} label="Copier Python" />
            </div>

            {/* Excel Format */}
            <div className="space-y-3">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Excel / Google Sheets</p>
              <div className="bg-slate-900 rounded-lg p-4 font-mono text-xs text-blue-400 break-all">
                {excelEq}
              </div>
              <CopyButton text={excelEq} label="Copier Excel" />
            </div>
          </div>
        </div>
      </div>

      <div className="space-y-8">
        {/* Fit Plots - Only for single variable regression */}
        {!isMultivariate && fitPlotsToRender.length > 0 && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {fitPlotsToRender.map(({ featureName, plotData }) => (
              <div key={featureName} className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
                <div className="mb-4">
                  <h3 className="text-xs font-bold text-slate-500 uppercase tracking-widest">
                    Ajustement : {featureName} vs Cible
                  </h3>
                  <p className="text-[11px] text-slate-400">
                    La ligne montre la fonction modélisée par rapport aux données réelles (points).
                  </p>
                </div>
                <div className="h-80 w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <ComposedChart data={plotData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                      <XAxis
                        type="number"
                        dataKey="x"
                        name={featureName}
                        label={{ value: featureName, position: 'bottom', offset: 0, fontSize: 10 }}
                        domain={['auto', 'auto']}
                        tickFormatter={(value) => value.toFixed(2)}
                        tick={{ fontSize: 9 }}
                      />
                      <YAxis
                        type="number"
                        label={{ value: 'Cible', angle: -90, position: 'left', offset: 0, fontSize: 10 }}
                        domain={['auto', 'auto']}
                        tickFormatter={(value) => value.toFixed(2)}
                        tick={{ fontSize: 9 }}
                      />
                      <Tooltip content={<CustomTooltip />} cursor={{ strokeDasharray: '3 3' }} />
                      <Legend wrapperStyle={{fontSize: '11px'}} />
                      <Scatter name="Données Réelles" dataKey="real" fill="#94a3b8" opacity={0.5} shape="circle" />
                      <Line name="Modèle (Fit)" type="monotone" dataKey="pred" stroke="#6366f1" strokeWidth={2} dot={false} />
                    </ComposedChart>
                  </ResponsiveContainer>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Partial Regression Plot - Only for multivariate regression */}
        {isMultivariate && partialFeatures.length > 0 && (
          <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
            <div className="mb-4">
              <div className="flex items-center justify-between mb-2">
                <div>
                  <h3 className="text-xs font-bold text-slate-500 uppercase tracking-widest">
                    Partial Regression Plot
                  </h3>
                  <p className="text-[11px] text-slate-400 mt-1">
                    Effet isolé de chaque variable, contrôlant les autres. La pente montre l'impact réel de la variable choisie.
                  </p>
                </div>
                <select
                  value={selectedPartialFeature}
                  onChange={(e) => setSelectedPartialFeature(e.target.value)}
                  className="px-3 py-2 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent bg-white"
                >
                  {partialFeatures.map((feature) => (
                    <option key={feature} value={feature}>
                      {feature}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            <div className="h-96 w-full">
              <ResponsiveContainer width="100%" height="100%">
                <ComposedChart
                  data={partial_regression_plots[selectedPartialFeature] || []}
                  margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
                >
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                  <XAxis
                    type="number"
                    dataKey="x"
                    label={{ value: `${selectedPartialFeature} (résidus)`, position: 'bottom', offset: 0, fontSize: 10 }}
                    domain={['auto', 'auto']}
                    tickFormatter={(value) => value.toFixed(2)}
                    tick={{ fontSize: 9 }}
                  />
                  <YAxis
                    type="number"
                    label={{ value: 'Cible (résidus)', angle: -90, position: 'left', offset: 0, fontSize: 10 }}
                    domain={['auto', 'auto']}
                    tickFormatter={(value) => value.toFixed(2)}
                    tick={{ fontSize: 9 }}
                  />
                  <Tooltip content={<CustomTooltip />} cursor={{ strokeDasharray: '3 3' }} />
                  <Legend wrapperStyle={{fontSize: '11px'}} />
                  <Scatter name="Données" fill="#94a3b8" opacity={0.5} shape="circle" />
                  <Line
                    name="Tendance (pente = coefficient)"
                    type="monotone"
                    dataKey="y"
                    stroke="#6366f1"
                    strokeWidth={2}
                    dot={false}
                  />
                </ComposedChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-3 p-3 bg-indigo-50 rounded-lg border border-indigo-100">
              <p className="text-[10px] text-indigo-700">
                <strong>Interprétation :</strong> Ce graphe montre la relation entre <code>{selectedPartialFeature}</code> et la cible,
                après avoir retiré l'effet de toutes les autres variables. Une pente positive indique que cette variable
                augmente la cible, indépendamment des autres facteurs.
              </p>
            </div>
          </div>
        )}

        {/* 3. Parity Plot (Real vs Predicted) - The Diagonal */}
        <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
          <div className="mb-4">
            <h3 className="text-xs font-bold text-slate-500 uppercase tracking-widest">Validation : Réel vs Prédit</h3>
            <p className="text-[11px] text-slate-400">
              Les points doivent s'aligner sur la diagonale rouge (Y = X).
            </p>
          </div>
          <div className="h-80 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <ScatterChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                <XAxis type="number" dataKey="real" name="Réel" label={{ value: 'Réel', position: 'bottom', offset: 0, fontSize: 10 }} domain={parityDomain} tickFormatter={(value) => value.toFixed(2)} tick={{ fontSize: 9 }} />
                <YAxis type="number" dataKey="pred" name="Prédit" label={{ value: 'Prédit', angle: -90, position: 'left', offset: 0, fontSize: 10 }} domain={parityDomain} tickFormatter={(value) => value.toFixed(2)} tick={{ fontSize: 9 }} />
                <Tooltip content={<CustomTooltip />} cursor={{ strokeDasharray: '3 3' }} />
                <ReferenceLine segment={[{ x: minParity, y: minParity }, { x: maxParity, y: maxParity }]} stroke="#ef4444" strokeDasharray="3 3" />
                <Scatter name="Observations" data={parityData} fill="#818cf8" opacity={0.6} />
              </ScatterChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* 4. Coefficients Table */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        <header className="p-4 border-b border-slate-100 bg-slate-50/50 flex items-center justify-between">
          <h3 className="text-xs font-bold text-slate-500 uppercase tracking-widest">Coefficients du Modèle</h3>
          <Info className="w-4 h-4 text-slate-300" />
        </header>
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="border-b border-slate-100 text-[10px] uppercase font-bold text-slate-400">
              <th className="px-6 py-3">Variable</th>
              <th className="px-6 py-3 text-right">Coefficient</th>
              <th className="px-6 py-3 text-right">P-Value</th>
              <th className="px-6 py-3 text-center">Fiabilité</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50">
            {Object.entries(coefficients || {}).map(([name, val]) => {
              const p = (analysisResults as any).p_values[name];
              const isSignificant = p < 0.05;
              return (
                <tr key={name} className="text-sm">
                  <td className="px-6 py-4 font-bold text-slate-700">{name}</td>
                  <td className="px-6 py-4 text-right font-mono">{Number(val).toFixed(4)}</td>
                  <td className={cn("px-6 py-4 text-right font-mono", isSignificant ? "text-emerald-600" : "text-rose-500")}>
                    {Number(p).toFixed(4)}
                  </td>
                  <td className="px-6 py-4 text-center">
                    {isSignificant ? (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-600 bg-emerald-50 px-2 py-1 rounded-full">
                        <CheckCircle2 className="w-3 h-3" /> FIABLE
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold text-slate-400 bg-slate-100 px-2 py-1 rounded-full">
                        <XCircle className="w-3 h-3" /> INCERTAIN
                      </span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
