"use client";

import React, { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Users,
  TrendingUp,
  Target,
  Award,
  BarChart3,
  ArrowLeft,
  Download,
  UserCheck,
  GraduationCap,
  Building2,
  Star,
  BookOpen,
  X,
  ChevronRight,
} from "lucide-react";
import { TechIcon } from "@/components/icons/tech-icon";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { loadTeams, loadSkillCategories } from "@/lib/data-loader";
import { Team, SkillCategory } from "@/lib/types";

interface TeamMember {
  id: string;
  firstName: string;
  lastName: string;
  skills: Array<{
    skillId: string;
    skillName: string;
    category: string;
    level: number;
    canMentor: boolean;
    wantsToLearn: boolean;
  }>;
  joinDate: string;
}

interface TeamStats {
  teamId: string;
  teamName: string;
  direction: string;
  totalMembers: number;
  averageSkillLevel: number;
  topSkills: Array<{ skillName: string; averageLevel: number }>;
  skillCoverage: number;
  members: TeamMember[];
}

function getSkillLevelLabel(level: number): string {
  if (level < 0.5) return "Débutant";
  if (level < 1.5) return "Intermé.";
  if (level < 2.5) return "Avancé";
  return "Expert";
}

function getSkillLevelColor(level: number): string {
  if (level < 0.5) return "bg-red-500";
  if (level < 1.5) return "bg-orange-500";
  if (level < 2.5) return "bg-blue-500";
  return "bg-green-500";
}

// Mock data generation (same as admin page)
function generateTeamMembers(
  teamName: string,
  memberCount: number,
  skillCategories: SkillCategory[]
) {
  const firstNames = [
    "Alice",
    "Bob",
    "Claire",
    "David",
    "Emma",
    "Frank",
    "Grace",
    "Hugo",
    "Iris",
    "Jack",
    "Kelly",
    "Liam",
    "Maya",
    "Noah",
    "Olivia",
    "Paul",
    "Quinn",
    "Rose",
    "Sam",
    "Tara",
  ];
  const lastNames = [
    "Martin",
    "Bernard",
    "Dubois",
    "Thomas",
    "Robert",
    "Richard",
    "Petit",
    "Durand",
    "Leroy",
    "Moreau",
    "Simon",
    "Laurent",
    "Michel",
    "Garcia",
    "David",
    "Bertrand",
    "Roux",
    "Vincent",
    "Fournier",
    "Morel",
  ];

  const allSkills: Array<{ skillName: string; category: string; id: string }> =
    [];
  skillCategories.forEach((category) => {
    category.skills.forEach((skill) => {
      allSkills.push({
        skillName: skill.name,
        category: category.category,
        id: skill.id,
      });
    });
  });

  return Array.from({ length: memberCount }, (_, index) => {
    const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
    const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];

    const skillCount = Math.floor(Math.random() * 8) + 8;
    const memberSkills = allSkills
      .sort(() => Math.random() - 0.5)
      .slice(0, skillCount)
      .map((skill) => ({
        skillId: skill.id,
        skillName: skill.skillName,
        category: skill.category,
        level: Math.floor(Math.random() * 4),
        canMentor: Math.random() > 0.7,
        wantsToLearn: Math.random() > 0.6,
      }));

    return {
      id: `${teamName}-member-${index + 1}`,
      firstName,
      lastName,
      skills: memberSkills,
      joinDate: new Date(
        Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000 * 3
      )
        .toISOString()
        .split("T")[0],
    };
  });
}

function getRandomSkills(skillCategories: SkillCategory[], count: number = 3) {
  const allSkills: Array<{ skillName: string; category: string }> = [];
  skillCategories.forEach((category) => {
    category.skills.forEach((skill) => {
      allSkills.push({ skillName: skill.name, category: category.category });
    });
  });

  const shuffled = allSkills.sort(() => Math.random() - 0.5);
  const randomSkills = shuffled.slice(0, count).map((skill) => ({
    skillName: skill.skillName,
    averageLevel: Math.random() * 3,
  }));

  return randomSkills.sort((a, b) => b.averageLevel - a.averageLevel);
}

export default function TeamDetailPage() {
  const params = useParams();
  const router = useRouter();
  const teamId = params.teamId as string;

  const [team, setTeam] = useState<TeamStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [skillAnalysis, setSkillAnalysis] = useState<any[]>([]);
  const [selectedMember, setSelectedMember] = useState<TeamMember | null>(null);
  const [isMemberModalOpen, setIsMemberModalOpen] = useState(false);

  useEffect(() => {
    async function loadTeamData() {
      try {
        const [teamsData, categoriesData] = await Promise.all([
          loadTeams(),
          loadSkillCategories(),
        ]);

        const foundTeam = teamsData.find((t) => t.id === teamId);
        if (!foundTeam) {
          router.push("/admin");
          return;
        }

        const memberCount = Math.floor(Math.random() * 10) + 3;
        const members = generateTeamMembers(
          foundTeam.name,
          memberCount,
          categoriesData
        );

        const teamStats: TeamStats = {
          teamId: foundTeam.id,
          teamName: foundTeam.name,
          direction: foundTeam.direction,
          totalMembers: memberCount,
          averageSkillLevel: Math.random() * 3,
          topSkills: getRandomSkills(categoriesData, 3),
          skillCoverage: Math.random() * 100,
          members: members,
        };

        setTeam(teamStats);

        // Analyser les compétences
        const skillMap = new Map();
        members.forEach((member) => {
          member.skills.forEach((skill) => {
            if (!skillMap.has(skill.skillName)) {
              // Trouver l'icône de la compétence dans les données
              let skillIcon = null;
              for (const category of categoriesData) {
                const foundSkill = category.skills.find(
                  (s) => s.name === skill.skillName
                );
                if (foundSkill) {
                  skillIcon = foundSkill.icon;
                  break;
                }
              }

              skillMap.set(skill.skillName, {
                skillName: skill.skillName,
                category: skill.category,
                icon: skillIcon,
                experts: [],
                learners: [],
                averageLevel: 0,
                totalEvaluations: 0,
              });
            }

            const skillData = skillMap.get(skill.skillName);
            skillData.totalEvaluations++;
            skillData.averageLevel += skill.level;

            if (skill.level >= 2) {
              skillData.experts.push({
                name: `${member.firstName} ${member.lastName}`,
                level: skill.level,
                canMentor: skill.canMentor,
              });
            }

            if (skill.wantsToLearn) {
              skillData.learners.push({
                name: `${member.firstName} ${member.lastName}`,
                currentLevel: skill.level,
              });
            }
          });
        });

        const skills = Array.from(skillMap.values())
          .map((skill) => ({
            ...skill,
            averageLevel: skill.averageLevel / skill.totalEvaluations,
          }))
          .sort((a, b) => b.averageLevel - a.averageLevel);

        setSkillAnalysis(skills);
      } catch (error) {
        console.error("Error loading team data:", error);
        router.push("/admin");
      } finally {
        setLoading(false);
      }
    }

    loadTeamData();
  }, [teamId, router]);

  const handleMemberClick = (member: TeamMember) => {
    setSelectedMember(member);
    setIsMemberModalOpen(true);
  };

  const handleCloseMemberModal = () => {
    setIsMemberModalOpen(false);
    setSelectedMember(null);
  };

  const handleExportReport = () => {
    if (!team) return;

    const reportData = {
      team: team.teamName,
      direction: team.direction,
      exportDate: new Date().toLocaleDateString(),
      summary: {
        totalMembers: team.totalMembers,
        averageSkillLevel: team.averageSkillLevel,
        skillCoverage: team.skillCoverage,
      },
      topSkills: team.topSkills,
      skillAnalysis: skillAnalysis.slice(0, 15),
      members: team.members.map((member) => ({
        name: `${member.firstName} ${member.lastName}`,
        joinDate: member.joinDate,
        skillsCount: member.skills.length,
        averageLevel:
          member.skills.reduce((sum, s) => sum + s.level, 0) /
          member.skills.length,
        skills: member.skills.map((skill) => ({
          skillName: skill.skillName,
          category: skill.category,
          level: skill.level,
          levelLabel: getSkillLevelLabel(skill.level),
          canMentor: skill.canMentor,
          wantsToLearn: skill.wantsToLearn,
        })),
      })),
      mentorshipOpportunities: skillAnalysis
        .filter(
          (skill) => skill.experts.length > 0 && skill.learners.length > 0
        )
        .map((skill) => ({
          skillName: skill.skillName,
          experts: skill.experts.filter((e) => e.canMentor),
          learners: skill.learners,
        })),
    };

    const dataStr = JSON.stringify(reportData, null, 2);
    const dataUri =
      "data:application/json;charset=utf-8," + encodeURIComponent(dataStr);

    const exportFileDefaultName = `rapport-complet-${team.teamName.toLowerCase()}-${
      new Date().toISOString().split("T")[0]
    }.json`;

    const linkElement = document.createElement("a");
    linkElement.setAttribute("href", dataUri);
    linkElement.setAttribute("download", exportFileDefaultName);
    linkElement.click();
  };

  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 p-6">
          <div className="flex items-center justify-center h-64">
            <div className="text-white">Chargement...</div>
          </div>
        </div>
      </div>
    );
  }

  if (!team) {
    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 p-6">
          <div className="text-center text-white">Équipe non trouvée</div>
        </div>
      </div>
    );
  }

  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 p-6 space-y-6">
        {/* Header */}
        <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Button
                variant="ghost"
                onClick={() => router.back()}
                className="text-slate-400 hover:text-white hover:bg-white/10"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                Retour
              </Button>
              <div className="flex items-center gap-3">
                <div className="p-3 bg-blue-500/20 border border-blue-500/30 rounded-xl">
                  <Users className="h-6 w-6 text-blue-400" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-white">
                    Équipe {team.teamName}
                  </h1>
                  <p className="text-slate-400">
                    {team.direction} • {team.totalMembers} membres
                  </p>
                </div>
              </div>
            </div>
            <Button
              onClick={handleExportReport}
              className="bg-blue-500 hover:bg-blue-600 text-white"
            >
              <Download className="h-4 w-4 mr-2" />
              Exporter rapport complet
            </Button>
          </div>
        </div>

        {/* Stats générales */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 text-center">
            <Users className="h-8 w-8 text-green-400 mx-auto mb-3" />
            <div className="text-3xl font-bold text-white">
              {team.totalMembers}
            </div>
            <div className="text-sm text-slate-400">Membres actifs</div>
          </div>
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 text-center">
            <BarChart3 className="h-8 w-8 text-blue-400 mx-auto mb-3" />
            <div className="text-3xl font-bold text-white">
              {((team.averageSkillLevel / 3) * 100).toFixed(0)}%
            </div>
            <div className="text-sm text-slate-400">Niveau moyen</div>
          </div>
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 text-center">
            <Target className="h-8 w-8 text-orange-400 mx-auto mb-3" />
            <div className="text-3xl font-bold text-white">
              {skillAnalysis.length}
            </div>
            <div className="text-sm text-slate-400">Compétences évaluées</div>
          </div>
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 text-center">
            <Award className="h-8 w-8 text-purple-400 mx-auto mb-3" />
            <div className="text-3xl font-bold text-white">
              {skillAnalysis.filter((s) => s.experts.length > 0).length}
            </div>
            <div className="text-sm text-slate-400">Expertises disponibles</div>
          </div>
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
          {/* Analyse des compétences */}
          <div className="xl:col-span-1">
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 h-fit">
              <div className="flex items-center gap-3 mb-6">
                <div className="p-2 bg-purple-500/20 border border-purple-500/30 rounded-xl">
                  <Award className="h-5 w-5 text-purple-400" />
                </div>
                <h2 className="text-xl font-bold text-white">
                  Top Compétences
                </h2>
              </div>
              <div className="space-y-3">
                {skillAnalysis.slice(0, 15).map((skill, idx) => (
                  <div
                    key={idx}
                    className="group p-4 bg-white/5 border border-white/10 rounded-xl hover:bg-white/10 hover:border-white/20 transition-all duration-200"
                  >
                    <div className="flex items-start gap-3">
                      {/* Icône de la technologie */}
                      <div className="flex-shrink-0 mt-0.5">
                        {skill.icon ? (
                          <div className="p-2 bg-white/10 border border-white/20 rounded-lg">
                            <TechIcon
                              iconName={skill.icon}
                              className="w-4 h-4 text-white"
                            />
                          </div>
                        ) : (
                          <div className="p-2 bg-slate-500/20 border border-slate-500/30 rounded-lg">
                            <Star className="w-4 h-4 text-slate-400" />
                          </div>
                        )}
                      </div>

                      {/* Contenu principal */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between mb-2">
                          <h3 className="text-white font-medium truncate pr-2">
                            {skill.skillName}
                          </h3>
                          <div className="flex items-center gap-2 flex-shrink-0">
                            <span className="text-sm font-semibold text-white">
                              {((skill.averageLevel / 3) * 100).toFixed(0)}%
                            </span>
                            <div
                              className={`w-2 h-2 rounded-full ${getSkillLevelColor(
                                skill.averageLevel
                              )}`}
                            />
                          </div>
                        </div>

                        {/* Barre de progression */}
                        <div className="w-full bg-white/10 rounded-full h-1.5 mb-3">
                          <div
                            className={`h-1.5 rounded-full transition-all ${
                              skill.averageLevel < 0.5
                                ? "bg-gradient-to-r from-red-500 to-red-400"
                                : skill.averageLevel < 1.5
                                ? "bg-gradient-to-r from-orange-500 to-orange-400"
                                : skill.averageLevel < 2.5
                                ? "bg-gradient-to-r from-blue-500 to-blue-400"
                                : "bg-gradient-to-r from-green-500 to-green-400"
                            }`}
                            style={{
                              width: `${(skill.averageLevel / 3) * 100}%`,
                            }}
                          />
                        </div>

                        {/* Métadonnées */}
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-slate-400 font-medium">
                            {skill.category}
                          </span>
                          <div className="flex items-center gap-3">
                            {skill.experts.length > 0 && (
                              <div className="flex items-center gap-1 text-green-400">
                                <GraduationCap className="w-3 h-3" />
                                <span className="font-medium">
                                  {skill.experts.length}
                                </span>
                              </div>
                            )}
                            {skill.learners.length > 0 && (
                              <div className="flex items-center gap-1 text-blue-400">
                                <BookOpen className="w-3 h-3" />
                                <span className="font-medium">
                                  {skill.learners.length}
                                </span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Experts et mentors */}
          <div className="xl:col-span-1">
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 h-fit">
              <div className="flex items-center gap-3 mb-6">
                <div className="p-2 bg-green-500/20 border border-green-500/30 rounded-xl">
                  <GraduationCap className="h-5 w-5 text-green-400" />
                </div>
                <h2 className="text-xl font-bold text-white">
                  Experts & Mentors
                </h2>
              </div>
              <div className="space-y-3">
                {skillAnalysis
                  .filter((skill) => skill.experts.length > 0)
                  .slice(0, 20)
                  .map((skill, idx) => (
                    <div
                      key={idx}
                      className="group p-4 bg-white/5 border border-white/10 rounded-xl hover:bg-white/10 hover:border-white/20 transition-all duration-200"
                    >
                      <div className="flex items-start gap-3 mb-3">
                        {/* Icône de la technologie */}
                        <div className="flex-shrink-0">
                          {skill.icon ? (
                            <div className="p-1.5 bg-white/10 border border-white/20 rounded-lg">
                              <TechIcon
                                iconName={skill.icon}
                                className="w-3.5 h-3.5 text-white"
                              />
                            </div>
                          ) : (
                            <div className="p-1.5 bg-slate-500/20 border border-slate-500/30 rounded-lg">
                              <Star className="w-3.5 h-3.5 text-slate-400" />
                            </div>
                          )}
                        </div>

                        {/* Nom de la compétence */}
                        <div className="flex-1">
                          <h3 className="font-semibold text-white text-sm">
                            {skill.skillName}
                          </h3>
                          <p className="text-xs text-slate-400">
                            {skill.category}
                          </p>
                        </div>

                        {/* Badge du nombre d'experts */}
                        <div className="flex-shrink-0">
                          <div className="px-2 py-1 bg-green-500/20 border border-green-500/30 rounded-lg">
                            <span className="text-xs font-medium text-green-300">
                              {skill.experts.length} expert
                              {skill.experts.length > 1 ? "s" : ""}
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Liste des experts */}
                      <div className="space-y-2 ml-8">
                        {skill.experts.map((expert, expertIdx) => (
                          <div
                            key={expertIdx}
                            className="flex items-center justify-between p-2 bg-white/5 rounded-lg"
                          >
                            <div className="flex items-center gap-2">
                              <div className="w-6 h-6 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                                <span className="text-xs font-bold text-white">
                                  {expert.name
                                    .split(" ")
                                    .map((n) => n[0])
                                    .join("")}
                                </span>
                              </div>
                              <span className="text-sm text-slate-200 font-medium">
                                {expert.name}
                              </span>
                            </div>
                            <div className="flex items-center gap-2">
                              <div
                                className={`px-2 py-0.5 rounded-md text-xs font-medium ${
                                  expert.level >= 3
                                    ? "bg-green-500/20 text-green-300 border border-green-500/30"
                                    : expert.level >= 2
                                    ? "bg-blue-500/20 text-blue-300 border border-blue-500/30"
                                    : "bg-orange-500/20 text-orange-300 border border-orange-500/30"
                                }`}
                              >
                                {getSkillLevelLabel(expert.level)}
                              </div>
                              {expert.canMentor && (
                                <div className="p-1 bg-green-500/20 border border-green-500/30 rounded">
                                  <GraduationCap className="w-3 h-3 text-green-400" />
                                </div>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
              </div>
            </div>
          </div>

          {/* Liste des membres */}
          <div className="xl:col-span-1">
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 h-fit">
              <div className="flex items-center gap-3 mb-6">
                <div className="p-2 bg-blue-500/20 border border-blue-500/30 rounded-xl">
                  <Users className="h-5 w-5 text-blue-400" />
                </div>
                <h2 className="text-xl font-bold text-white">
                  Membres de l'équipe
                </h2>
              </div>
              <div className="space-y-3">
                {team.members.map((member, idx) => {
                  const avgLevel =
                    member.skills.reduce((sum, s) => sum + s.level, 0) /
                    member.skills.length;
                  const mentorSkills = member.skills.filter(
                    (s) => s.canMentor
                  ).length;
                  const learningSkills = member.skills.filter(
                    (s) => s.wantsToLearn
                  ).length;

                  return (
                    <div
                      key={idx}
                      onClick={() => handleMemberClick(member)}
                      className="group p-4 bg-white/5 border border-white/10 rounded-xl hover:bg-white/10 hover:border-white/20 transition-all duration-200 cursor-pointer"
                    >
                      <div className="flex items-start gap-3">
                        {/* Avatar */}
                        <div className="flex-shrink-0">
                          <div className="w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center">
                            <span className="text-sm font-bold text-white">
                              {member.firstName[0]}
                              {member.lastName[0]}
                            </span>
                          </div>
                        </div>

                        {/* Informations principales */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between mb-2">
                            <h3 className="font-semibold text-white truncate">
                              {member.firstName} {member.lastName}
                            </h3>
                            <div className="flex items-center gap-2 flex-shrink-0">
                              <span className="text-xs font-semibold text-white">
                                {((avgLevel / 3) * 100).toFixed(0)}%
                              </span>
                              <div
                                className={`w-2 h-2 rounded-full ${getSkillLevelColor(
                                  avgLevel
                                )}`}
                              />
                              <ChevronRight className="w-4 h-4 text-slate-400 group-hover:text-white transition-colors" />
                            </div>
                          </div>

                          {/* Date d'arrivée */}
                          <p className="text-xs text-slate-400 mb-3">
                            Membre depuis{" "}
                            {new Date(member.joinDate).toLocaleDateString(
                              "fr-FR",
                              {
                                year: "numeric",
                                month: "long",
                              }
                            )}
                          </p>

                          {/* Barre de progression du niveau */}
                          <div className="w-full bg-white/10 rounded-full h-1.5 mb-3">
                            <div
                              className={`h-1.5 rounded-full transition-all ${
                                avgLevel < 0.5
                                  ? "bg-gradient-to-r from-red-500 to-red-400"
                                  : avgLevel < 1.5
                                  ? "bg-gradient-to-r from-orange-500 to-orange-400"
                                  : avgLevel < 2.5
                                  ? "bg-gradient-to-r from-blue-500 to-blue-400"
                                  : "bg-gradient-to-r from-green-500 to-green-400"
                              }`}
                              style={{ width: `${(avgLevel / 3) * 100}%` }}
                            />
                          </div>

                          {/* Statistiques */}
                          <div className="grid grid-cols-3 gap-3 text-xs">
                            <div className="text-center p-2 bg-white/5 rounded-lg">
                              <div className="text-white font-semibold">
                                {member.skills.length}
                              </div>
                              <div className="text-slate-400">Compétences</div>
                            </div>
                            <div className="text-center p-2 bg-green-500/10 border border-green-500/20 rounded-lg">
                              <div className="text-green-300 font-semibold">
                                {mentorSkills}
                              </div>
                              <div className="text-green-400">Mentor</div>
                            </div>
                            <div className="text-center p-2 bg-blue-500/10 border border-blue-500/20 rounded-lg">
                              <div className="text-blue-300 font-semibold">
                                {learningSkills}
                              </div>
                              <div className="text-blue-400">Apprend</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Modal des détails du membre */}
      <Dialog open={isMemberModalOpen} onOpenChange={setIsMemberModalOpen}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto bg-slate-900 border-slate-700">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold text-white flex items-center gap-3">
              {selectedMember && (
                <>
                  <div className="w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center">
                    <span className="text-sm font-bold text-white">
                      {selectedMember.firstName[0]}
                      {selectedMember.lastName[0]}
                    </span>
                  </div>
                  <div>
                    <h2 className="text-white">
                      {selectedMember.firstName} {selectedMember.lastName}
                    </h2>
                    <p className="text-sm text-slate-400 font-normal">
                      {selectedMember.skills.length} compétences évaluées
                    </p>
                  </div>
                </>
              )}
            </DialogTitle>
          </DialogHeader>

          {selectedMember && (
            <div className="space-y-6 mt-6">
              {/* Statistiques rapides */}
              <div className="grid grid-cols-3 gap-4">
                <div className="bg-white/5 border border-white/10 rounded-xl p-4 text-center">
                  <div className="text-2xl font-bold text-white">
                    {selectedMember.skills.length}
                  </div>
                  <div className="text-sm text-slate-400">Compétences</div>
                </div>
                <div className="bg-green-500/10 border border-green-500/20 rounded-xl p-4 text-center">
                  <div className="text-2xl font-bold text-green-300">
                    {selectedMember.skills.filter((s) => s.canMentor).length}
                  </div>
                  <div className="text-sm text-green-400">Peut mentorer</div>
                </div>
                <div className="bg-blue-500/10 border border-blue-500/20 rounded-xl p-4 text-center">
                  <div className="text-2xl font-bold text-blue-300">
                    {selectedMember.skills.filter((s) => s.wantsToLearn).length}
                  </div>
                  <div className="text-sm text-blue-400">Veut apprendre</div>
                </div>
              </div>

              {/* Liste des compétences par catégorie */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                  <Award className="w-5 h-5 text-purple-400" />
                  Compétences détaillées
                </h3>

                {/* Grouper les compétences par catégorie */}
                {Object.entries(
                  selectedMember.skills.reduce((acc, skill) => {
                    if (!acc[skill.category]) {
                      acc[skill.category] = [];
                    }
                    acc[skill.category].push(skill);
                    return acc;
                  }, {} as Record<string, typeof selectedMember.skills>)
                ).map(([category, skills]) => (
                  <div
                    key={category}
                    className="bg-white/5 border border-white/10 rounded-xl p-4"
                  >
                    <h4 className="font-semibold text-white mb-4 flex items-center gap-2">
                      <div className="w-2 h-2 bg-blue-400 rounded-full"></div>
                      {category}
                      <span className="text-sm text-slate-400 font-normal">
                        ({skills.length} compétence
                        {skills.length > 1 ? "s" : ""})
                      </span>
                    </h4>

                    <div className="space-y-2">
                      {skills
                        .sort((a, b) => b.level - a.level)
                        .map((skill, skillIdx) => {
                          // Trouver l'icône de la compétence
                          let skillIcon = null;
                          if (skillAnalysis.length > 0) {
                            const foundSkill = skillAnalysis.find(
                              (s) => s.skillName === skill.skillName
                            );
                            if (foundSkill) {
                              skillIcon = foundSkill.icon;
                            }
                          }

                          return (
                            <div
                              key={skillIdx}
                              className="flex items-center gap-3 p-2 hover:bg-white/5 rounded-lg transition-colors"
                            >
                              {/* Icône de la technologie */}
                              <div className="flex-shrink-0">
                                {skillIcon ? (
                                  <TechIcon
                                    iconName={skillIcon}
                                    className="w-4 h-4 text-white"
                                  />
                                ) : (
                                  <Star className="w-4 h-4 text-slate-400" />
                                )}
                              </div>

                              {/* Nom de la compétence */}
                              <div className="flex-1 min-w-0">
                                <span className="text-sm font-medium text-white truncate">
                                  {skill.skillName}
                                </span>
                              </div>

                              {/* Niveau et badges */}
                              <div className="flex items-center gap-2 flex-shrink-0">
                                {/* Badge de niveau */}
                                <div
                                  className={`px-2 py-0.5 rounded text-xs font-medium ${
                                    skill.level >= 3
                                      ? "bg-green-500/20 text-green-300"
                                      : skill.level >= 2
                                      ? "bg-blue-500/20 text-blue-300"
                                      : skill.level >= 1
                                      ? "bg-orange-500/20 text-orange-300"
                                      : "bg-red-500/20 text-red-300"
                                  }`}
                                >
                                  {getSkillLevelLabel(skill.level)}
                                </div>

                                {/* Icônes mentor/apprenant */}
                                {skill.canMentor && (
                                  <div className="p-1 bg-green-500/20 rounded">
                                    <GraduationCap className="w-3 h-3 text-green-400" />
                                  </div>
                                )}
                                {skill.wantsToLearn && (
                                  <div className="p-1 bg-blue-500/20 rounded">
                                    <BookOpen className="w-3 h-3 text-blue-400" />
                                  </div>
                                )}
                              </div>
                            </div>
                          );
                        })}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
