"use client";

import React, { useState, useEffect } from "react";
import {
  X,
  Search,
  BookOpen,
  FileText,
  ArrowRight,
  ChevronRight,
  ExternalLink,
} from "lucide-react";
import { cn } from "@/lib/utils";
import * as Dialog from "@radix-ui/react-dialog";

// Types pour la structure de documentation
interface DocSection {
  id: string;
  title: string;
  description?: string;
  icon?: React.ReactNode;
  children?: DocSection[];
  content?: string;
}

// Structure de documentation basée sur les fichiers markdown
const DOCUMENTATION_STRUCTURE: DocSection[] = [
  {
    id: "getting-started",
    title: "Démarrage Rapide",
    icon: <BookOpen className="w-5 h-5" />,
    children: [
      {
        id: "import-data",
        title: "Importer vos données",
        description: "Formats supportés : CSV, Excel",
        content: "user-guide#importer-vos-données",
      },
      {
        id: "explore-data",
        title: "Explorer vos données",
        description: "Table intelligente et détection d'outliers",
        content: "user-guide#explorer-vos-données",
      },
      {
        id: "start-analysis",
        title: "Lancer une analyse",
        description: "Corrélation et régression",
        content: "user-guide#lancer-une-analyse",
      },
    ],
  },
  {
    id: "correlation",
    title: "Analyse de Corrélation",
    icon: <FileText className="w-5 h-5" />,
    children: [
      {
        id: "correlation-methods",
        title: "Méthodes de corrélation",
        description: "Pearson, Spearman, Kendall",
        content: "correlation-guide#les-trois-méthodes",
      },
      {
        id: "interpret-heatmap",
        title: "Interpréter la heatmap",
        description: "Comprendre les couleurs et valeurs",
        content: "correlation-guide#interpréter-la-matrice",
      },
      {
        id: "multicollinearity",
        title: "Multicolinéarité",
        description: "Détecter et éviter les corrélations entre prédicteurs",
        content: "correlation-guide#multicolinéarité",
      },
      {
        id: "p-values",
        title: "P-values et significativité",
        description: "Comprendre la significativité statistique",
        content: "correlation-guide#p-values-et-significativité",
      },
    ],
  },
  {
    id: "regression",
    title: "Régression Statistique",
    icon: <FileText className="w-5 h-5" />,
    children: [
      {
        id: "model-types",
        title: "Types de modèles",
        description: "Linéaire, logistique, polynomial, exponentielle",
        content: "regression-guide#types-de-modèles",
      },
      {
        id: "configure-model",
        title: "Configuration du modèle",
        description: "Choisir cible et prédicteurs",
        content: "regression-guide#configuration-du-modèle",
      },
      {
        id: "interpret-results",
        title: "Interpréter les résultats",
        description: "R², coefficients, p-values",
        content: "regression-guide#interprétation-des-résultats",
      },
      {
        id: "model-equations",
        title: "Équations du modèle",
        description: "Exporter en Python, Excel, LaTeX",
        content: "regression-guide#équations-du-modèle",
      },
    ],
  },
  {
    id: "outliers",
    title: "Gestion des Outliers",
    icon: <FileText className="w-5 h-5" />,
    children: [
      {
        id: "outlier-types",
        title: "Types d'outliers",
        description: "Univariés vs multivariés",
        content: "outlier-guide#types-doutliers",
      },
      {
        id: "detection-methods",
        title: "Méthodes de détection",
        description: "IQR et Isolation Forest",
        content: "outlier-guide#méthodes-de-détection",
      },
      {
        id: "visual-indicators",
        title: "Indicateurs visuels",
        description: "Cercles rouge et violet",
        content: "outlier-guide#indicateurs-visuels",
      },
      {
        id: "manage-outliers",
        title: "Gérer les outliers",
        description: "Processus d'exclusion",
        content: "outlier-guide#processus-de-gestion",
      },
    ],
  },
];

interface HelpPanelProps {
  /**
   * Contrôle l'ouverture du panel
   */
  open?: boolean;
  /**
   * Callback lors de la fermeture
   */
  onOpenChange?: (open: boolean) => void;
}

export function HelpPanel({ open: controlledOpen, onOpenChange }: HelpPanelProps) {
  const [internalOpen, setInternalOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [expandedSections, setExpandedSections] = useState<Set<string>>(
    new Set(["getting-started"])
  );

  const open = controlledOpen !== undefined ? controlledOpen : internalOpen;

  const setOpen = (newOpen: boolean) => {
    if (controlledOpen === undefined) {
      setInternalOpen(newOpen);
    }
    onOpenChange?.(newOpen);
  };

  const toggleSection = (sectionId: string) => {
    setExpandedSections((prev) => {
      const next = new Set(prev);
      if (next.has(sectionId)) {
        next.delete(sectionId);
      } else {
        next.add(sectionId);
      }
      return next;
    });
  };

  // Filtrer les sections basées sur la recherche
  const filteredStructure = searchQuery
    ? DOCUMENTATION_STRUCTURE.map((section) => ({
        ...section,
        children: section.children?.filter(
          (child) =>
            child.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
            child.description?.toLowerCase().includes(searchQuery.toLowerCase())
        ),
      })).filter((section) => (section.children?.length || 0) > 0)
    : DOCUMENTATION_STRUCTURE;

  // Ouvrir automatiquement les sections lors de la recherche
  useEffect(() => {
    if (searchQuery) {
      setExpandedSections(new Set(filteredStructure.map((s) => s.id)));
    }
  }, [searchQuery, filteredStructure]);

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Portal>
        <Dialog.Overlay
          className={cn(
            "fixed inset-0 bg-black/20 backdrop-blur-sm z-40",
            "transition-opacity duration-200",
            open ? "opacity-100" : "opacity-0 pointer-events-none"
          )}
          onClick={() => setOpen(false)}
        />
        <Dialog.Content
          className={cn(
            "fixed top-0 right-0 bottom-0 w-[480px] max-w-[90vw] bg-white z-50",
            "shadow-2xl border-l border-slate-200",
            "transition-transform duration-200 ease-out",
            open ? "translate-x-0" : "translate-x-full"
          )}
        >
          {/* Header */}
          <div className="sticky top-0 bg-white border-b border-slate-200 px-6 py-4 z-10">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white font-bold shadow-md">
                  ?
                </div>
                <div>
                  <Dialog.Title className="text-lg font-bold text-slate-900">
                    Centre d'Aide
                  </Dialog.Title>
                  <Dialog.Description className="text-sm text-slate-500">
                    Guides et documentation
                  </Dialog.Description>
                </div>
              </div>
              <Dialog.Close
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center",
                  "text-slate-400 hover:text-slate-700 hover:bg-slate-100",
                  "transition-colors duration-150"
                )}
              >
                <X className="w-5 h-5" />
              </Dialog.Close>
            </div>

            {/* Search */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <input
                type="text"
                placeholder="Rechercher dans les guides..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className={cn(
                  "w-full pl-10 pr-4 py-2.5 rounded-lg",
                  "bg-slate-50 border border-slate-200",
                  "text-sm text-slate-900 placeholder:text-slate-400",
                  "focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent",
                  "transition-all duration-150"
                )}
              />
            </div>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto px-6 py-4">
            <div className="space-y-2">
              {filteredStructure.map((section) => {
                const isExpanded = expandedSections.has(section.id);
                const hasChildren = section.children && section.children.length > 0;

                return (
                  <div key={section.id} className="border border-slate-200 rounded-lg overflow-hidden">
                    {/* Section Header */}
                    <button
                      onClick={() => toggleSection(section.id)}
                      disabled={!hasChildren}
                      className={cn(
                        "w-full flex items-center justify-between px-4 py-3",
                        "bg-slate-50 hover:bg-slate-100",
                        "transition-colors duration-150",
                        !hasChildren && "cursor-default"
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <div className={cn(
                          "w-8 h-8 rounded-lg flex items-center justify-center",
                          "bg-indigo-100 text-indigo-600"
                        )}>
                          {section.icon}
                        </div>
                        <span className="font-semibold text-sm text-slate-900">
                          {section.title}
                        </span>
                      </div>
                      {hasChildren && (
                        <ChevronRight
                          className={cn(
                            "w-4 h-4 text-slate-400 transition-transform duration-200",
                            isExpanded && "rotate-90"
                          )}
                        />
                      )}
                    </button>

                    {/* Section Children */}
                    {isExpanded && hasChildren && (
                      <div className="border-t border-slate-200 bg-white divide-y divide-slate-100">
                        {section.children!.map((child) => (
                          <a
                            key={child.id}
                            href={`/docs/${child.content}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className={cn(
                              "flex items-start gap-3 px-4 py-3",
                              "hover:bg-indigo-50/50",
                              "transition-colors duration-150",
                              "group"
                            )}
                          >
                            <div className="flex-1 space-y-1">
                              <div className="flex items-center justify-between">
                                <span className="text-sm font-medium text-slate-900 group-hover:text-indigo-700 transition-colors">
                                  {child.title}
                                </span>
                                <ExternalLink className="w-3.5 h-3.5 text-slate-400 group-hover:text-indigo-600 transition-colors shrink-0" />
                              </div>
                              {child.description && (
                                <p className="text-xs text-slate-500 leading-relaxed">
                                  {child.description}
                                </p>
                              )}
                            </div>
                          </a>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}

              {filteredStructure.length === 0 && (
                <div className="text-center py-12">
                  <Search className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                  <p className="text-sm text-slate-500">Aucun résultat pour &quot;{searchQuery}&quot;</p>
                </div>
              )}
            </div>
          </div>

          {/* Footer */}
          <div className="sticky bottom-0 bg-white border-t border-slate-200 px-6 py-4">
            <a
              href="/docs/readme"
              target="_blank"
              rel="noopener noreferrer"
              className={cn(
                "flex items-center justify-center gap-2 w-full",
                "px-4 py-2.5 rounded-lg",
                "bg-gradient-to-r from-indigo-600 to-purple-600",
                "text-white text-sm font-semibold",
                "hover:from-indigo-700 hover:to-purple-700",
                "transition-all duration-150",
                "shadow-md hover:shadow-lg"
              )}
            >
              <BookOpen className="w-4 h-4" />
              <span>Voir toute la documentation</span>
              <ArrowRight className="w-4 h-4" />
            </a>
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
