"use client";

import React, { useEffect, useState, useMemo } from "react";
import { useGridStore, ModelType } from "@/store/use-grid-store";
import { Wand2, Target, CheckCircle2, ChevronRight, BarChart3, AlertCircle, Settings2, GitBranch, Lightbulb, Sparkles } from "lucide-react";
import { cn, safeJSONStringify } from "@/lib/utils";
import { getApiUrl } from "@/lib/api-config";
import { analyzeAndRecommendModel, ModelRecommendation } from "@/lib/model-recommendation";

interface AnalysisConfigurationProps {
  onRun: () => void;
  onShowCorrelation?: () => void;
}

export function AnalysisConfiguration({ onRun, onShowCorrelation }: AnalysisConfigurationProps) {
  const { 
    columns, 
    getCleanData, 
    targetVariable, 
    setTargetVariable, 
    selectedFeatures, 
    setSelectedFeatures,
    modelType,
    setModelType,
    polyDegree,
    setPolyDegree,
    includeInteractions,
    setIncludeInteractions
  } = useGridStore();
  
  const [importances, setImportances] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [showCorrelationHint, setShowCorrelationHint] = useState(false);
  const [recommendation, setRecommendation] = useState<ModelRecommendation | null>(null);
  const [autoApplyRecommendation, setAutoApplyRecommendation] = useState(true);

  const numericCols = columns.filter(c => c.type === 'numeric');
  const targetCol = columns.find(c => c.name === targetVariable);

  // Validation Logic
  const validationError = useMemo(() => {
    if (!targetCol) return null;
    if (['linear', 'polynomial', 'exponential'].includes(modelType) && targetCol.type !== 'numeric') {
      return "Ce modèle nécessite une cible numérique continue.";
    }
    if (modelType === 'logistic') {
      if (targetCol.type !== 'categorical' && targetCol.type !== 'boolean') {
        return "La régression logistique nécessite une cible catégorique ou binaire.";
      }
    }
    return null;
  }, [targetCol, modelType]);

  const isReady = targetVariable && selectedFeatures.length > 0 && !validationError;

  useEffect(() => {
    if (!targetVariable || numericCols.length < 2) {
      setImportances([]);
      return;
    }

    const fetchImportance = async () => {
      setLoading(true);
      try {
        const features = numericCols.map(c => c.name).filter(n => n !== targetVariable);
        const response = await fetch(getApiUrl("/analysis/feature-importance"), {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: safeJSONStringify({ data: getCleanData(), features, target: targetVariable })
        });
        const result = await response.json();
        setImportances(result.importances);
        setSelectedFeatures(result.importances.slice(0, 5).map((i: any) => i.feature));
      } catch (e) {
        console.error("Feature importance failed", e);
      } finally {
        setLoading(false);
      }
    };

    fetchImportance();
  }, [targetVariable, getCleanData, numericCols.length, setSelectedFeatures]);

  // Show correlation hint when target is selected
  useEffect(() => {
    if (targetVariable && numericCols.length >= 2) {
      setShowCorrelationHint(true);
    }
  }, [targetVariable, numericCols.length]);

  // Auto-detect best model type when target changes
  useEffect(() => {
    if (!targetVariable) {
      setRecommendation(null);
      return;
    }

    // Analyser et recommander le meilleur modèle
    const rec = analyzeAndRecommendModel(
      useGridStore.getState().data,
      columns,
      targetVariable
    );

    if (rec && autoApplyRecommendation) {
      // Appliquer automatiquement les recommandations
      if (rec.recommendedType !== modelType) {
        setModelType(rec.recommendedType);
      }
      if (rec.polynomialDegree && rec.polynomialDegree !== polyDegree) {
        setPolyDegree(rec.polynomialDegree);
      }
      if (rec.recommendedInteractions.length > 0 && !includeInteractions) {
        setIncludeInteractions(true);
      }
    }

    setRecommendation(rec);
  }, [targetVariable, columns, modelType, polyDegree, includeInteractions, setModelType, setPolyDegree, setIncludeInteractions, autoApplyRecommendation]);

  return (
    <div className="w-[350px] bg-white border-l border-slate-200 h-full flex flex-col shadow-2xl z-30 animate-in slide-in-from-right duration-300">
      <header className="p-4 border-b border-slate-100 flex items-center gap-2">
        <Target className="w-5 h-5 text-indigo-600" />
        <h3 className="font-bold text-slate-800 text-sm">Configuration Avancée</h3>
      </header>

      <div className="flex-1 overflow-y-auto p-6 space-y-8">
        {/* Step 0: Model Type */}
        <section className="space-y-3">
          <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-2">
            <BarChart3 className="w-3 h-3" />
            Modèle & Complexité
          </p>
          <div className="grid grid-cols-2 gap-2 bg-slate-100 p-1 rounded-xl mb-4">
            {(['linear', 'logistic', 'polynomial', 'exponential'] as const).map((type) => (
              <button 
                key={type}
                onClick={() => setModelType(type)}
                className={cn(
                  "py-1.5 rounded-lg text-[11px] font-bold transition-all capitalize",
                  modelType === type ? "bg-white text-indigo-600 shadow-sm" : "text-slate-500 hover:text-slate-700"
                )}
              >
                {type}
              </button>
            ))}
          </div>

          {/* Advanced Options for Polynomial/Linear */}
          {(modelType === 'polynomial' || modelType === 'linear') && (
            <div className="bg-slate-50 p-3 rounded-lg border border-slate-100 space-y-3 animate-in fade-in">
              {modelType === 'polynomial' && (
                <div className="flex items-center justify-between">
                  <label className="text-xs font-medium text-slate-700">Degré du Polynôme</label>
                  <div className="flex items-center gap-2">
                    <button 
                      onClick={() => setPolyDegree(Math.max(2, polyDegree - 1))}
                      className="w-6 h-6 bg-white border rounded text-xs hover:bg-slate-50"
                    >-</button>
                    <span className="text-xs font-mono font-bold w-4 text-center">{polyDegree}</span>
                    <button 
                      onClick={() => setPolyDegree(Math.min(5, polyDegree + 1))}
                      className="w-6 h-6 bg-white border rounded text-xs hover:bg-slate-50"
                    >+</button>
                  </div>
                </div>
              )}
              
              <div className="flex items-center gap-2">
                <input 
                  type="checkbox" 
                  id="interactions"
                  checked={includeInteractions}
                  onChange={(e) => setIncludeInteractions(e.target.checked)}
                  className="rounded text-indigo-600 focus:ring-indigo-500"
                />
                <label htmlFor="interactions" className="text-xs text-slate-600">
                  Inclure intéractions (x*y)
                </label>
              </div>
            </div>
          )}
        </section>

        {/* AI Recommendation Section */}
        {recommendation && (
          <section className="animate-in fade-in slide-in-from-top-2 duration-500">
            <div className={cn(
              "p-4 rounded-xl border space-y-3",
              recommendation.recommendedType === modelType
                ? "bg-gradient-to-br from-emerald-50 to-teal-50 border-emerald-200"
                : "bg-gradient-to-br from-amber-50 to-orange-50 border-amber-200"
            )}>
              <div className="flex items-start gap-3">
                <div className={cn(
                  "p-2 rounded-lg",
                  recommendation.recommendedType === modelType
                    ? "bg-emerald-100 text-emerald-600"
                    : "bg-amber-100 text-amber-600"
                )}>
                  <Sparkles className="w-5 h-5" />
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <p className="text-sm font-bold text-slate-800">
                      {recommendation.recommendedType === modelType
                        ? "✅ Configuration optimale détectée"
                        : "💡 Recommandation IA"}
                    </p>
                    {recommendation.confidence >= 0.8 && (
                      <span className="text-[9px] px-2 py-0.5 bg-emerald-100 text-emerald-700 rounded-full font-medium">
                        {Math.round(recommendation.confidence * 100)}% confiant
                      </span>
                    )}
                  </div>

                  {recommendation.recommendedType !== modelType && (
                    <button
                      onClick={() => {
                        setModelType(recommendation.recommendedType);
                        if (recommendation.polynomialDegree) setPolyDegree(recommendation.polynomialDegree);
                      }}
                      className="text-[10px] text-emerald-700 hover:text-emerald-800 font-medium underline mb-2"
                    >
                      Appliquer la recommandation →
                    </button>
                  )}

                  <div className="space-y-1 text-[10px] text-slate-700 leading-relaxed">
                    {recommendation.reasons.map((reason, i) => (
                      <p key={i}>{reason}</p>
                    ))}
                  </div>

                  {recommendation.recommendedInteractions.length > 0 && (
                    <div className="mt-2 p-2 bg-white/50 rounded-lg">
                      <p className="text-[9px] font-medium text-slate-600 mb-1">
                        🔗 Interactions suggérées :
                      </p>
                      <div className="flex flex-wrap gap-1">
                        {recommendation.recommendedInteractions.map((pair, i) => (
                          <span
                            key={i}
                            className="text-[9px] px-2 py-0.5 bg-indigo-100 text-indigo-700 rounded"
                          >
                            {pair[0]} × {pair[1]}
                          </span>
                        ))}
                      </div>
                      {!includeInteractions && (
                        <button
                          onClick={() => setIncludeInteractions(true)}
                          className="text-[9px] text-indigo-600 hover:text-indigo-800 underline mt-1"
                        >
                          Activer les interactions →
                        </button>
                      )}
                    </div>
                  )}

                  {recommendation.warnings.length > 0 && (
                    <div className="mt-2 p-2 bg-amber-100/50 rounded-lg">
                      {recommendation.warnings.map((warning, i) => (
                        <p key={i} className="text-[9px] text-amber-800">{warning}</p>
                      ))}
                    </div>
                  )}

                  <div className="flex items-center gap-2 mt-2 pt-2 border-t border-black/5">
                    <input
                      type="checkbox"
                      id="auto-apply"
                      checked={autoApplyRecommendation}
                      onChange={(e) => setAutoApplyRecommendation(e.target.checked)}
                      className="rounded text-emerald-600 focus:ring-emerald-500 text-xs"
                    />
                    <label htmlFor="auto-apply" className="text-[10px] text-slate-600 cursor-pointer">
                      Appliquer automatiquement les recommandations
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </section>
        )}

        {/* Step 1: Select Y */}
        <section className="space-y-3">
          <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-2">
            <span className="w-4 h-4 bg-slate-100 rounded-full flex items-center justify-center text-slate-500 text-[9px]">1</span>
            Variable Cible (Y)
          </p>
          <select 
            className={cn(
              "w-full p-2 bg-slate-50 border rounded-lg text-sm outline-none transition-all",
              validationError ? "border-rose-300 text-rose-600" : "border-slate-200 focus:border-indigo-500"
            )}
            value={targetVariable || ""}
            onChange={(e) => setTargetVariable(e.target.value || null)}
          >
            <option value="">Sélectionner une cible...</option>
            {columns.map(c => (
              <option key={c.name} value={c.name}>{c.name}</option>
            ))}
          </select>
          {validationError && (
            <div className="flex items-start gap-2 p-2 bg-rose-50 text-[10px] text-rose-600 rounded-lg border border-rose-100">
              <AlertCircle className="w-3 h-3 shrink-0 mt-0.5" />
              <span>{validationError}</span>
            </div>
          )}
        </section>

        {/* Step 2: Select X with recommendations */}
        {targetVariable && (
          <section className="space-y-4 animate-in fade-in slide-in-from-top-2 duration-500">
            <div className="flex items-center justify-between">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-2">
                <span className="w-4 h-4 bg-slate-100 rounded-full flex items-center justify-center text-slate-500 text-[9px]">2</span>
                Prédicteurs (X)
              </p>
              <Wand2 className={cn("w-4 h-4 text-indigo-400", loading && "animate-spin")} />
            </div>

            {loading ? (
              <div className="space-y-2">
                {[1,2,3].map(i => <div key={i} className="h-8 bg-slate-50 animate-pulse rounded-lg" />)}
              </div>
            ) : (
              <div className="space-y-2">
                {importances.length > 0 ? importances.map((imp) => (
                  <label 
                    key={imp.feature} 
                    className={cn(
                      "flex flex-col gap-1 p-2 rounded-lg border cursor-pointer transition-all",
                      selectedFeatures.includes(imp.feature) ? "bg-indigo-50 border-indigo-200" : "bg-white border-slate-100 hover:border-slate-200"
                    )}
                  >
                    <div className="flex items-center gap-3">
                      <input 
                        type="checkbox" 
                        className="rounded text-indigo-600 border-slate-300 focus:ring-indigo-500"
                        checked={selectedFeatures.includes(imp.feature)}
                        onChange={(e) => {
                          if (e.target.checked) setSelectedFeatures([...selectedFeatures, imp.feature]);
                          else setSelectedFeatures(selectedFeatures.filter(f => f !== imp.feature));
                        }}
                      />
                      <span className="text-xs font-medium text-slate-700 flex-1">{imp.feature}</span>
                      <span className="text-[10px] font-mono text-slate-400">{(imp.score * 100).toFixed(1)}%</span>
                    </div>
                    <div className="h-1 w-full bg-slate-100 rounded-full overflow-hidden">
                      <div className="h-full bg-indigo-400" style={{ width: `${imp.score * 100}%` }} />
                    </div>
                  </label>
                )) : (
                  <div className="text-[10px] text-slate-400 italic text-center p-4">
                    Aucune recommandation disponible. Sélectionnez des prédicteurs manuellement.
                  </div>
                )}
              </div>
            )}
          </section>
        )}

        {/* Correlation Hint - Show when target is selected */}
        {showCorrelationHint && onShowCorrelation && (
          <section className="animate-in fade-in slide-in-from-top-2 duration-500">
            <div className="bg-gradient-to-br from-indigo-50 to-purple-50 p-4 rounded-xl border border-indigo-100 space-y-3">
              <div className="flex items-start gap-3">
                <GitBranch className="w-5 h-5 text-indigo-600 shrink-0 mt-0.5" />
                <div className="flex-1">
                  <p className="text-xs font-bold text-slate-800 mb-1">
                    Analysez les corrélations avant de lancer
                  </p>
                  <p className="text-[10px] text-slate-600 leading-relaxed">
                    Visualisez la matrice de corrélation pour identifier les relations entre variables
                    et éviter la multicolinéarité.
                  </p>
                </div>
              </div>
              <button
                onClick={onShowCorrelation}
                className="w-full py-2.5 bg-white border border-indigo-200 rounded-lg text-xs font-bold text-indigo-700 hover:bg-indigo-50 transition-all flex items-center justify-center gap-2"
              >
                <GitBranch className="w-3.5 h-3.5" />
                Voir la matrice de corrélation
              </button>
            </div>
          </section>
        )}
      </div>

      <footer className="p-6 border-t border-slate-100 bg-slate-50/50">
        <button 
          disabled={!isReady}
          onClick={onRun}
          className={cn(
            "w-full py-3 rounded-xl text-sm font-bold shadow-lg flex items-center justify-center gap-2 transition-all",
            isReady ? "bg-indigo-600 text-white hover:bg-indigo-700 shadow-indigo-100" : "bg-slate-200 text-slate-400 cursor-not-allowed shadow-none"
          )}
        >
          Lancer l'Analyse
          <ChevronRight className="w-4 h-4" />
        </button>
      </footer>
    </div>
  );
}