"use client";

import { useEffect, useState } from "react";
import { useEvaluation } from "@/hooks/use-evaluation";
import { SkillsRadarChart } from "@/components/radar-chart";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { generateRadarData } from "@/lib/evaluation-utils";
import { useUser } from "@/hooks/use-user-context";
import { TechIcon } from "@/components/icons/tech-icon";
import Link from "next/link";
import { Code2, ChevronDown, ChevronRight, ExternalLink } from "lucide-react";
import { getCategoryIcon } from "@/lib/category-icons";

// Fonction pour déterminer la couleur du badge selon le niveau moyen
function getScoreColors(score: number) {
  if (score >= 2.5) {
    // Expert/Maîtrise (violet)
    return {
      bg: "bg-violet-500/20",
      border: "border-violet-500/30",
      text: "text-violet-400",
      gradient: "from-violet-500 to-violet-400",
    };
  } else if (score >= 1.5) {
    // Autonome (vert)
    return {
      bg: "bg-green-500/20",
      border: "border-green-500/30",
      text: "text-green-400",
      gradient: "from-green-500 to-green-400",
    };
  } else if (score >= 0.5) {
    // Non autonome (orange/amber)
    return {
      bg: "bg-amber-500/20",
      border: "border-amber-500/30",
      text: "text-amber-400",
      gradient: "from-amber-500 to-amber-400",
    };
  } else {
    // Jamais pratiqué (rouge)
    return {
      bg: "bg-red-500/20",
      border: "border-red-500/30",
      text: "text-red-400",
      gradient: "from-red-500 to-red-400",
    };
  }
}

export default function HomePage() {
  const { userEvaluation, skillCategories, teams, loading } = useEvaluation();

  const { setUserInfo } = useUser();
  const [expandedCategory, setExpandedCategory] = useState<string | null>(null);

  // Update user info in navigation when user evaluation is loaded
  useEffect(() => {
    if (userEvaluation) {
      const teamName =
        teams.find((t) => t.id === userEvaluation.profile.teamId)?.name || "";
      setUserInfo({
        firstName: userEvaluation.profile.firstName,
        lastName: userEvaluation.profile.lastName,
        teamName,
      });
    } else {
      setUserInfo(null);
    }
  }, [userEvaluation, teams, setUserInfo]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
        <div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />

        <div className="relative z-10 container mx-auto py-16 px-6">
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-400 mx-auto mb-4"></div>
              <p className="text-white">Chargement...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!userEvaluation) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
        <div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />

        <div className="relative z-10 container mx-auto py-16 px-6">
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-400 mx-auto mb-4"></div>
              <p className="text-white">
                Redirection vers la page de connexion...
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const radarData = generateRadarData(
    userEvaluation.evaluations,
    skillCategories
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
      {/* Background Effects */}
      <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
      <div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />
      <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent" />

      <div className="relative z-10 container mx-auto px-6 py-8 max-w-7xl space-y-8">
        {/* Header */}
        <div className="text-center space-y-4 mb-12">
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/5 border border-white/10 backdrop-blur-sm">
            <Code2 className="h-4 w-4 text-blue-400" />
            <span className="text-sm font-medium text-slate-200">
              Tableau de bord
            </span>
          </div>

          <h1 className="text-4xl font-bold text-white">
            Bonjour {userEvaluation.profile.firstName} !
          </h1>

          <p className="text-slate-400 max-w-2xl mx-auto leading-relaxed">
            Voici un aperçu de vos compétences techniques
          </p>
        </div>

        {/* Main Content Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Radar Chart */}
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
            <div className="mb-6">
              <h3 className="text-xl font-bold text-white mb-2">
                Vue d'ensemble de vos compétences
              </h3>
              <p className="text-slate-400 text-sm">
                Radar chart représentant votre niveau par catégorie
              </p>
            </div>
            <div className="h-80">
              <SkillsRadarChart data={radarData} />
            </div>
          </div>

          {/* Category Breakdown */}
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
            <div className="mb-6">
              <h3 className="text-xl font-bold text-white mb-2">
                Détail par catégorie
              </h3>
              <p className="text-slate-400 text-sm">
                Vue détaillée de votre progression dans chaque domaine
              </p>
            </div>
            <div className="space-y-3">
              {radarData.map((category) => {
                const categoryEval = userEvaluation.evaluations.find(
                  (e) => e.category === category.category
                );
                const skillsCount = categoryEval?.selectedSkillIds?.length || 0;
                const evaluatedCount =
                  categoryEval?.skills.filter((s) => s.level !== null).length ||
                  0;
                const isExpanded = expandedCategory === category.category;
                const currentSkillCategory = skillCategories.find(
                  (sc) => sc.category === category.category
                );
                const CategoryIcon = currentSkillCategory
                  ? getCategoryIcon(currentSkillCategory.icon)
                  : null;

                return (
                  <div
                    key={category.category}
                    className="bg-white/5 border border-white/10 rounded-lg overflow-hidden transition-colors"
                  >
                    <div
                      className="p-3 hover:bg-white/10 transition-colors cursor-pointer"
                      onClick={() =>
                        setExpandedCategory(
                          isExpanded ? null : category.category
                        )
                      }
                    >
                      <div className="flex justify-between items-center mb-2">
                        <div className="flex items-center gap-2">
                          {isExpanded ? (
                            <ChevronDown className="h-4 w-4 text-slate-400" />
                          ) : (
                            <ChevronRight className="h-4 w-4 text-slate-400" />
                          )}
                          {CategoryIcon && (
                            <CategoryIcon className="h-4 w-4 text-blue-400" />
                          )}
                          <h4 className="font-medium text-white text-sm">
                            {category.category}
                          </h4>
                        </div>
                        {skillsCount > 0 ? (
                          (() => {
                            const colors = getScoreColors(category.score);
                            return (
                              <div
                                className={`px-2 py-0.5 rounded-full ${colors.bg} border ${colors.border}`}
                              >
                                <span
                                  className={`text-xs font-medium ${colors.text}`}
                                >
                                  {Math.round((category.score / 3) * 100)}%
                                </span>
                              </div>
                            );
                          })()
                        ) : (
                          <div className="px-2 py-0.5 rounded-full bg-slate-500/20 border border-slate-500/30">
                            <span className="text-xs font-medium text-slate-400">
                              Aucune
                            </span>
                          </div>
                        )}
                      </div>
                      <div className="text-xs text-slate-400 mb-2">
                        {skillsCount > 0
                          ? `${evaluatedCount}/${skillsCount} compétences sélectionnées évaluées`
                          : "Aucune compétence sélectionnée"}
                      </div>
                      {skillsCount > 0 ? (
                        <div className="w-full bg-white/10 rounded-full h-1.5">
                          {(() => {
                            const colors = getScoreColors(category.score);
                            return (
                              <div
                                className={`bg-gradient-to-r ${colors.gradient} h-1.5 rounded-full transition-all`}
                                style={{
                                  width: `${
                                    (category.score / category.maxScore) * 100
                                  }%`,
                                }}
                              ></div>
                            );
                          })()}
                        </div>
                      ) : (
                        <div className="w-full bg-slate-500/10 rounded-full h-1.5"></div>
                      )}
                    </div>

                    {/* Expanded Skills */}
                    {isExpanded && categoryEval && currentSkillCategory && (
                      <div className="px-3 pb-3 border-t border-white/10 bg-white/5">
                        <div className="pt-3 space-y-2 max-h-60 overflow-y-auto">
                          {categoryEval.selectedSkillIds.map((skillId) => {
                            const skill = currentSkillCategory.skills.find(
                              (s) => s.id === skillId
                            );
                            if (!skill) return null;

                            const skillEval = categoryEval.skills.find(
                              (s) => s.skillId === skillId
                            );
                            return (
                              <div
                                key={skillId}
                                className="flex items-center justify-between p-2 bg-white/5 border border-white/10 rounded-lg"
                              >
                                <div className="flex items-center gap-2">
                                  <TechIcon
                                    iconName={skill.icon}
                                    className="w-4 h-4 text-blue-400"
                                    fallbackText={skill.name}
                                  />
                                  <span className="text-sm text-white">
                                    {skill.name}
                                  </span>
                                </div>
                                <div className="flex items-center gap-2">
                                  {skillEval?.level && (
                                    <span className="text-xs text-slate-400">
                                      {skillEval.level === "never" &&
                                        "Jamais utilisé"}
                                      {skillEval.level === "not-autonomous" &&
                                        "Non autonome"}
                                      {skillEval.level === "autonomous" &&
                                        "Autonome"}
                                      {skillEval.level === "expert" && "Expert"}
                                    </span>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </div>

                        <div className="mt-3 pt-3 border-t border-white/10">
                          <Button
                            asChild
                            className="w-full bg-blue-500 hover:bg-blue-600 text-white"
                          >
                            <Link
                              href={`/evaluation?category=${encodeURIComponent(
                                category.category
                              )}`}
                            >
                              <ExternalLink className="w-4 h-4 mr-2" />
                              Évaluer {category.category}
                            </Link>
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Action Button */}
        <div className="flex justify-center mt-12">
          <Button
            asChild
            size="lg"
            className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 rounded-xl"
          >
            <Link href="/evaluation">Continuer l'évaluation</Link>
          </Button>
        </div>
      </div>
    </div>
  );
}
