"use client";

import React, { useState, useEffect, useCallback } from "react";
import { FileUploader } from "@/features/uploader/components/FileUploader";
import { SmartGrid } from "@/features/smart-grid/components/SmartGrid";
import { InsightPanel } from "@/features/insight-panel/components/InsightPanel";
import { CorrelationHeatmap } from "@/features/analysis/components/CorrelationHeatmap";
import { AnalysisConfiguration } from "@/features/analysis/components/AnalysisConfiguration";
import { AnalysisResults } from "@/features/analysis/components/AnalysisResults";
import { HelpButton, HelpPanel, WelcomeTour } from "@/features/help";
import { useGridStore } from "@/store/use-grid-store";
import { useStore } from "zustand";
import { Undo2, Redo2, Wand2, Table as TableIcon, GitBranch, LineChart, Download, AlertTriangle, HelpCircle, BookOpen } from "lucide-react";
import { cn, safeJSONStringify } from "@/lib/utils";
import { getApiUrl } from "@/lib/api-config";

export default function Home() {
  const {
    data,
    columns,
    error,
    setError,
    setOutliers,
    setMultivariateOutliers,
    getCleanData,
    targetVariable,
    selectedFeatures,
    modelType,
    polyDegree,
    includeInteractions,
    setAnalysisResults,
    analysisResults,
    excludedRows
  } = useGridStore();
  const [insightCol, setInsightCol] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<"grid" | "correlation" | "results">("grid");
  const [isConfigOpen, setIsConfigOpen] = useState(false);
  const [isRunning, setIsRunning] = useState(false);
  const [isHelpOpen, setIsHelpOpen] = useState(false);
  
  const temporalStore = (useGridStore as any).temporal;
  const { undo, redo, pastStates, futureStates } = useStore(temporalStore, (state: any) => state);

  // Trigger Outlier Detection on data change OR when rows are excluded
  useEffect(() => {
    if (data.length > 0 && columns.length > 0) {
      const triggerDetection = async () => {
        const numericCols = columns.filter(c => c.type === 'numeric').map(c => c.name);
        if (numericCols.length === 0) return;

        // Send original data + excluded indices to backend
        // Backend will filter excluded rows and return outliers with correct original indices
        const excludedIndicesList = Array.from(excludedRows);

        try {
          const response = await fetch(getApiUrl("/analysis/detect-outliers"), {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: safeJSONStringify({
              data: data,
              columns: numericCols,
              method: "both",
              excluded_indices: excludedIndicesList
            })
          });
          const result = await response.json();

          // NEW STRUCTURED APPROACH:
          // 1. Store univariate outliers per column (column-specific)
          if (result.univariate) {
            numericCols.forEach(col => {
              const colOutliers = result.univariate[col] || [];
              setOutliers(col, colOutliers);
            });
          }

          // 2. Store multivariate outliers separately (global anomalies)
          if (result.multivariate) {
            setMultivariateOutliers(result.multivariate);
          }
        } catch (e) {
          console.error("Outlier detection failed", e);
        }
      };
      triggerDetection();
    }
  }, [data, columns, excludedRows, setOutliers, setMultivariateOutliers]);

  const onRunRegression = useCallback(async () => {
    if (!targetVariable || selectedFeatures.length === 0) {
        setError("Veuillez sélectionner une cible et au moins une feature.");
        return;
    }

    setIsRunning(true);
    setError(null);

    try {
      const payload = { 
          data: getCleanData(), 
          x_features: selectedFeatures, 
          y_target: targetVariable,
          model_type: modelType,
          poly_degree: polyDegree,
          include_interactions: includeInteractions
      };
      
      const response = await fetch(getApiUrl("/analysis/run-regression"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: safeJSONStringify(payload)
      });
      
      const result = await response.json();
      
      if (!response.ok) {
          throw new Error(result.detail || "Erreur lors de l'exécution du modèle.");
      }

      if (result.status === "ok") {
        setAnalysisResults({ ...result.results, model_type: modelType });
        setIsConfigOpen(false);
        setActiveTab("results");
      }
    } catch (e: any) {
      console.error("Regression failed", e);
      setError(`Erreur d'analyse: ${e.message}`);
    } finally {
      setIsRunning(false);
    }
  }, [getCleanData, targetVariable, selectedFeatures, modelType, setAnalysisResults, setError]);

  const onShowCorrelation = useCallback(() => {
    setActiveTab("correlation");
  }, [setActiveTab]);

  const onExportPDF = useCallback(async () => {
    if (!analysisResults) return;

    try {
      const response = await fetch(getApiUrl("/reports/export"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: safeJSONStringify({
          project_name: "Analysis_Result",
          results: analysisResults,
          audit_trail: {
            excluded_rows_count: excludedRows.size
          }
        })
      });

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `Report_Data_analysis_${Date.now()}.pdf`;
      document.body.appendChild(a);
      a.click();
      a.remove();
    } catch (e) {
      console.error("Export failed", e);
    }
  }, [analysisResults, excludedRows.size]);

  return (
    <div className="flex flex-col h-screen bg-slate-50 font-sans selection:bg-indigo-100 selection:text-indigo-900">
      
      {/*Navbar with Glassmorphism */}
      <header className="h-16 border-b border-slate-200 bg-white/80 backdrop-blur-md sticky top-0 z-50 flex items-center justify-between px-8 shadow-sm">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-lg flex items-center justify-center text-white font-bold shadow-md shadow-indigo-200">
            DA
          </div>
          <h1 className="text-lg font-bold text-slate-800 tracking-tight">Data_analysis</h1>
        </div>

        <div className="flex items-center gap-4">
          <div className="flex items-center bg-slate-100/50 p-1 rounded-lg border border-slate-200/50">
            <button
              onClick={() => undo()}
              disabled={pastStates.length === 0}
              className="p-2 text-slate-500 hover:text-indigo-600 hover:bg-white disabled:opacity-30 rounded-md transition-all"
              title="Annuler (Ctrl+Z)"
            >
              <Undo2 className="w-4 h-4" />
            </button>
            <button
              onClick={() => redo()}
              disabled={futureStates.length === 0}
              className="p-2 text-slate-500 hover:text-indigo-600 hover:bg-white disabled:opacity-30 rounded-md transition-all"
              title="Rétablir (Ctrl+Y)"
            >
              <Redo2 className="w-4 h-4" />
            </button>
          </div>

          {/* Help Button */}
          <div className="relative">
            <button
              data-tour-target="help-button"
              onClick={() => setIsHelpOpen(!isHelpOpen)}
              className={cn(
                "flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-bold transition-all border",
                isHelpOpen
                  ? "bg-indigo-100 text-indigo-700 border-indigo-300"
                  : "text-slate-600 hover:text-indigo-600 hover:bg-indigo-50 border-slate-200 bg-white"
              )}
              title="Ouvrir l'aide"
            >
              <BookOpen className="w-4 h-4" />
              Aide
            </button>
          </div>

          {analysisResults && (
            <button
              onClick={onExportPDF}
              className="flex items-center gap-2 text-slate-600 hover:text-indigo-600 hover:bg-indigo-50 px-4 py-2 rounded-lg text-xs font-bold transition-all border border-slate-200 bg-white shadow-sm"
            >
              <Download className="w-4 h-4" />
              Rapport PDF
            </button>
          )}

          <button
            data-tour-target="analyze-button"
            onClick={() => setIsConfigOpen(!isConfigOpen)}
            className={cn(
              "flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all shadow-lg hover:shadow-xl hover:-translate-y-0.5 active:translate-y-0",
              isConfigOpen
                ? "bg-slate-800 text-white shadow-slate-200"
                : "bg-gradient-to-r from-indigo-600 to-purple-600 text-white shadow-indigo-200"
            )}
          >
            <Wand2 className="w-4 h-4" />
            {isConfigOpen ? "Fermer Config" : "Lancer Analyse"}
          </button>
        </div>
      </header>

      {/* Main Layout */}
      <main className="flex-1 flex flex-row overflow-hidden relative bg-slate-50">
        <div className="flex-1 flex flex-col p-6 overflow-hidden gap-6 max-w-[1600px] mx-auto w-full">
          
          {/* Top Section: Upload & Tabs */}
          <div className="flex flex-col md:flex-row items-stretch gap-6">
            <div className="flex-1 min-w-[300px]" data-tour-target="upload">
              <FileUploader />
            </div>
            
            {/* Elegant Tabs */}
            <div className="flex bg-white p-1.5 rounded-2xl shadow-sm border border-slate-100 h-fit self-center" data-tour-target="tabs">
              {[{"id": "grid", "label": "Données", "icon": TableIcon },
                {"id": "correlation", "label": "Corrélations", "icon": GitBranch },
                {"id": "results", "label": "Résultats", "icon": LineChart },].map((tab) => (
                <button 
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={cn(
                    "flex items-center gap-2 px-6 py-3 rounded-xl text-xs font-bold transition-all",
                    activeTab === tab.id 
                      ? "bg-indigo-50 text-indigo-700 shadow-sm ring-1 ring-indigo-100" 
                      : "text-slate-500 hover:text-slate-900 hover:bg-slate-50"
                  )}
                >
                  <tab.icon className="w-4 h-4" />
                  {tab.label}
                </button>
              ))}
            </div>
          </div>

          {/* Error Banner */}
          {error && (
            <div className="flex items-center gap-3 p-4 bg-rose-50 border border-rose-100 text-rose-700 rounded-xl shadow-sm animate-in slide-in-from-top-2">
              <AlertTriangle className="w-5 h-5 shrink-0" />
              <p className="text-sm font-medium">{error}</p>
            </div>
          )}

          {/* Content Area */}
          <section className="flex-1 bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden relative">
            {activeTab === "grid" && (
              <div className="flex flex-col h-full">
                <div className="h-12 border-b border-slate-100 flex items-center justify-between px-6 bg-slate-50/50">
                  <h2 className="text-xs font-bold text-slate-400 uppercase tracking-widest flex items-center gap-2">
                    <TableIcon className="w-3 h-3" />
                    Vue Tabulaire
                  </h2>
                  {data.length > 0 && (
                    <span className="text-[10px] font-mono font-medium text-slate-500 bg-white px-2 py-1 rounded border border-slate-200 shadow-sm">
                      {data.length.toLocaleString()} rows • {columns.length} cols
                    </span>
                  )}
                </div>
                <div data-tour-target="grid">
                  <SmartGrid onShowInsights={(col) => setInsightCol(col)} />
                </div>
              </div>
            )}
            {activeTab === "correlation" && (
              <div className="p-6 h-full overflow-auto">
                <CorrelationHeatmap />
              </div>
            )}
            {activeTab === "results" && (
              <div className="p-6 h-full overflow-auto">
                <AnalysisResults />
              </div>
            )}
          </section>
        </div>

        {/* Overlays */}
        {isConfigOpen && <AnalysisConfiguration onRun={onRunRegression} onShowCorrelation={onShowCorrelation} />}
        {insightCol && <InsightPanel colName={insightCol} onClose={() => setInsightCol(null)} />}
        <HelpPanel open={isHelpOpen} onOpenChange={setIsHelpOpen} />
        <WelcomeTour />
      </main>
    </div>
  );
}
