"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Users,
  TrendingUp,
  Target,
  Award,
  BarChart3,
  ArrowLeft,
  Download,
  UserCheck,
  GraduationCap,
  Building2,
  Star,
  BookOpen,
  X,
  User,
  Brain,
  Coffee,
  Lightbulb,
  MessageSquare,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { TeamStats, TeamMember } from "@/services/admin-service";
import { TechIcon } from "@/components/icons/tech-icon";

interface TeamDetailClientWrapperProps {
  team: TeamStats;
  teamId: string;
}

interface SkillAnalysis {
  skillName: string;
  category: string;
  experts: Array<{
    name: string;
    level: number;
    canMentor: boolean;
  }>;
  learners: Array<{
    name: string;
    currentLevel: number;
  }>;
  averageLevel: number;
  totalEvaluations: number;
  expertCount: number;
  learnerCount: number;
  proficiencyRate: number;
}

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";
}

function getSkillLevelBadgeClasses(level: number): string {
  if (level < 0.5) return "bg-red-500/20 border-red-500/30 text-red-300";
  if (level < 1.5)
    return "bg-orange-500/20 border-orange-500/30 text-orange-300";
  if (level < 2.5) return "bg-blue-500/20 border-blue-500/30 text-blue-300";
  return "bg-green-500/20 border-green-500/30 text-green-300";
}

export function TeamDetailClientWrapper({
  team,
  teamId,
}: TeamDetailClientWrapperProps) {
  const router = useRouter();
  const [skillAnalysis, setSkillAnalysis] = useState<SkillAnalysis[]>([]);
  const [selectedMember, setSelectedMember] = useState<TeamMember | null>(null);
  const [isMemberModalOpen, setIsMemberModalOpen] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<string>("all");

  useEffect(() => {
    // Analyser les compétences avec les vraies données
    const skillMap = new Map<string, any>();

    team.members.forEach((member) => {
      member.skills.forEach((skill) => {
        if (!skillMap.has(skill.skillName)) {
          skillMap.set(skill.skillName, {
            skillName: skill.skillName,
            category: skill.category,
            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): SkillAnalysis => ({
          ...skill,
          averageLevel: skill.averageLevel / skill.totalEvaluations,
          expertCount: skill.experts.length,
          learnerCount: skill.learners.length,
          proficiencyRate:
            (skill.experts.length / skill.totalEvaluations) * 100,
        })
      )
      .sort((a, b) => b.averageLevel - a.averageLevel);

    setSkillAnalysis(skills);
  }, [team]);

  const handleExportReport = () => {
    const reportData = {
      team: team.teamName,
      direction: team.direction,
      exportDate: new Date().toLocaleDateString(),
      detailedStats: {
        totalMembers: team.totalMembers,
        averageSkillLevel: team.averageSkillLevel,
        skillCoverage: team.skillCoverage,
        expertiseDistribution: {
          beginners: team.members.filter(
            (m) =>
              m.skills.reduce((avg, s) => avg + s.level, 0) / m.skills.length <
              1
          ).length,
          intermediate: team.members.filter((m) => {
            const avg =
              m.skills.reduce((avg, s) => avg + s.level, 0) / m.skills.length;
            return avg >= 1 && avg < 2;
          }).length,
          advanced: team.members.filter((m) => {
            const avg =
              m.skills.reduce((avg, s) => avg + s.level, 0) / m.skills.length;
            return avg >= 2 && avg < 3;
          }).length,
          experts: team.members.filter(
            (m) =>
              m.skills.reduce((avg, s) => avg + s.level, 0) / m.skills.length >=
              3
          ).length,
        },
      },
      members: team.members.map((member) => ({
        name: `${member.firstName} ${member.lastName}`,
        joinDate: member.joinDate,
        skillCount: member.skills.length,
        averageLevel:
          member.skills.reduce((avg, s) => avg + s.level, 0) /
          member.skills.length,
        expertSkills: member.skills.filter((s) => s.level >= 2 && s.canMentor)
          .length,
        learningGoals: member.skills.filter((s) => s.wantsToLearn).length,
        skills: member.skills,
      })),
      skillAnalysis: skillAnalysis.map((skill) => ({
        name: skill.skillName,
        category: skill.category,
        averageLevel: skill.averageLevel,
        totalEvaluations: skill.totalEvaluations,
        expertCount: skill.expertCount,
        learnerCount: skill.learnerCount,
        proficiencyRate: skill.proficiencyRate,
        experts: skill.experts,
        learners: skill.learners,
      })),
      insights: {
        topPerformingSkills: skillAnalysis.slice(0, 5).map((s) => ({
          name: s.skillName,
          level: s.averageLevel,
          proficiency: s.proficiencyRate,
        })),
        skillsNeedingDevelopment: skillAnalysis
          .filter((s) => s.averageLevel < 1.5)
          .slice(0, 5)
          .map((s) => ({
            name: s.skillName,
            level: s.averageLevel,
            learners: s.learnerCount,
          })),
        mentorshipOpportunities: skillAnalysis
          .filter((s) => s.experts.filter((e) => e.canMentor).length > 0)
          .map((s) => ({
            skill: s.skillName,
            mentors: s.experts.filter((e) => e.canMentor).map((e) => e.name),
            potentialMentees: s.learners.map((l) => l.name),
          })),
      },
    };

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

    const exportFileDefaultName = `rapport-detaille-${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();
  };

  const categories = Array.from(new Set(skillAnalysis.map((s) => s.category)));
  const filteredSkills =
    selectedCategory === "all"
      ? skillAnalysis
      : skillAnalysis.filter((s) => s.category === selectedCategory);

  const teamInsights = {
    averageTeamLevel:
      team.members.reduce((sum, member) => {
        const memberAvg =
          member.skills.reduce((s, skill) => s + skill.level, 0) /
          member.skills.length;
        return sum + memberAvg;
      }, 0) / team.members.length,
    totalExperts: team.members.reduce(
      (sum, member) =>
        sum + member.skills.filter((s) => s.level >= 2 && s.canMentor).length,
      0
    ),
    totalLearners: team.members.reduce(
      (sum, member) => sum + member.skills.filter((s) => s.wantsToLearn).length,
      0
    ),
    skillGaps: skillAnalysis.filter((s) => s.averageLevel < 1.5).length,
    strongSkills: skillAnalysis.filter((s) => s.averageLevel >= 2.5).length,
  };

  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 avec breadcrumb et actions */}
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => router.push("/admin")}
              className="text-slate-400 hover:text-white hover:bg-white/10"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Retour à l'admin
            </Button>
            <div className="text-slate-400 text-sm">|</div>
            <div className="flex items-center gap-3">
              <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>
              <div>
                <h1 className="text-2xl font-bold text-white">
                  {team.teamName}
                </h1>
                <p className="text-slate-400">{team.direction}</p>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              onClick={handleExportReport}
              className="bg-white/5 border-white/20 text-white hover:bg-white/10"
            >
              <Download className="h-4 w-4 mr-2" />
              Rapport détaillé
            </Button>
          </div>
        </div>

        {/* Métriques principales */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6">
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 hover:bg-white/10 transition-colors">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-green-500/20 border border-green-500/30 rounded-xl">
                <Users className="h-4 w-4 text-green-400" />
              </div>
              <span className="text-slate-300 font-medium text-sm">
                Membres
              </span>
            </div>
            <div className="text-2xl font-bold text-white">
              {team.totalMembers}
            </div>
            <div className="text-xs text-slate-400 mt-1">personnes actives</div>
          </div>

          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 hover:bg-white/10 transition-colors">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-blue-500/20 border border-blue-500/30 rounded-xl">
                <BarChart3 className="h-4 w-4 text-blue-400" />
              </div>
              <span className="text-slate-300 font-medium text-sm">
                Niveau équipe
              </span>
            </div>
            <div className="text-2xl font-bold text-white">
              {((teamInsights.averageTeamLevel / 3) * 100).toFixed(0)}%
            </div>
            <div className="text-xs text-slate-400 mt-1">
              {getSkillLevelLabel(teamInsights.averageTeamLevel)}
            </div>
          </div>

          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 hover:bg-white/10 transition-colors">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-orange-500/20 border border-orange-500/30 rounded-xl">
                <Award className="h-4 w-4 text-orange-400" />
              </div>
              <span className="text-slate-300 font-medium text-sm">
                Expertises
              </span>
            </div>
            <div className="text-2xl font-bold text-white">
              {teamInsights.totalExperts}
            </div>
            <div className="text-xs text-slate-400 mt-1">
              compétences expertes
            </div>
          </div>

          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 hover:bg-white/10 transition-colors">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-purple-500/20 border border-purple-500/30 rounded-xl">
                <BookOpen className="h-4 w-4 text-purple-400" />
              </div>
              <span className="text-slate-300 font-medium text-sm">
                Apprentissages
              </span>
            </div>
            <div className="text-2xl font-bold text-white">
              {teamInsights.totalLearners}
            </div>
            <div className="text-xs text-slate-400 mt-1">
              objectifs d'apprentissage
            </div>
          </div>

          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 hover:bg-white/10 transition-colors">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-red-500/20 border border-red-500/30 rounded-xl">
                <Target className="h-4 w-4 text-red-400" />
              </div>
              <span className="text-slate-300 font-medium text-sm">
                Lacunes
              </span>
            </div>
            <div className="text-2xl font-bold text-white">
              {teamInsights.skillGaps}
            </div>
            <div className="text-xs text-slate-400 mt-1">
              compétences à renforcer
            </div>
          </div>
        </div>

        {/* Contenu principal avec onglets */}
        <Tabs defaultValue="overview" className="w-full">
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-1 mb-6 w-fit mx-auto">
            <TabsList className="grid w-full grid-cols-4 bg-transparent border-0">
              <TabsTrigger
                value="overview"
                className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-slate-400 hover:text-white transition-colors"
              >
                Vue d'ensemble
              </TabsTrigger>
              <TabsTrigger
                value="skills"
                className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-slate-400 hover:text-white transition-colors"
              >
                Compétences
              </TabsTrigger>
              <TabsTrigger
                value="members"
                className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-slate-400 hover:text-white transition-colors"
              >
                Membres
              </TabsTrigger>
              <TabsTrigger
                value="insights"
                className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-slate-400 hover:text-white transition-colors"
              >
                Insights
              </TabsTrigger>
            </TabsList>
          </div>

          {/* Onglet Vue d'ensemble */}
          <TabsContent value="overview" className="space-y-6">
            {/* Top Skills avec design amélioré */}
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Star className="h-5 w-5 text-yellow-400" />
                Top Compétences de l'équipe
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {team.topSkills.slice(0, 6).map((skill, idx) => (
                  <div
                    key={idx}
                    className="bg-white/5 border border-white/10 rounded-xl p-4 hover:bg-white/10 transition-colors group"
                  >
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        {skill.icon && (
                          <div className="p-1.5 bg-white/10 border border-white/20 rounded-md">
                            <TechIcon
                              iconName={skill.icon}
                              className="w-3 h-3 text-white"
                            />
                          </div>
                        )}
                        <span className="text-white font-medium text-sm group-hover:text-white transition-colors">
                          {skill.skillName}
                        </span>
                      </div>
                      <div
                        className={`w-3 h-3 rounded-full ${getSkillLevelColor(
                          skill.averageLevel
                        )}`}
                      />
                    </div>
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-2xl font-bold text-white">
                          {skill.averageLevel.toFixed(1)}
                        </span>
                        <span className="text-xs text-slate-400">
                          {getSkillLevelLabel(skill.averageLevel)}
                        </span>
                      </div>
                      <div className="w-full bg-white/10 rounded-full h-2">
                        <div
                          className={`h-2 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>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Distribution des niveaux */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
                <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                  <BarChart3 className="h-5 w-5 text-blue-400" />
                  Répartition des niveaux
                </h3>
                <div className="space-y-4">
                  {[
                    {
                      label: "Expert",
                      count: team.members.filter(
                        (m) =>
                          m.skills.reduce((avg, s) => avg + s.level, 0) /
                            m.skills.length >=
                          2.5
                      ).length,
                      color: "bg-green-500",
                    },
                    {
                      label: "Avancé",
                      count: team.members.filter((m) => {
                        const avg =
                          m.skills.reduce((avg, s) => avg + s.level, 0) /
                          m.skills.length;
                        return avg >= 2 && avg < 2.5;
                      }).length,
                      color: "bg-blue-500",
                    },
                    {
                      label: "Intermédiaire",
                      count: team.members.filter((m) => {
                        const avg =
                          m.skills.reduce((avg, s) => avg + s.level, 0) /
                          m.skills.length;
                        return avg >= 1 && avg < 2;
                      }).length,
                      color: "bg-orange-500",
                    },
                    {
                      label: "Débutant",
                      count: team.members.filter(
                        (m) =>
                          m.skills.reduce((avg, s) => avg + s.level, 0) /
                            m.skills.length <
                          1
                      ).length,
                      color: "bg-red-500",
                    },
                  ].map((level, idx) => (
                    <div
                      key={idx}
                      className="flex items-center justify-between p-3 bg-white/5 rounded-lg"
                    >
                      <div className="flex items-center gap-3">
                        <div
                          className={`w-3 h-3 rounded-full ${level.color}`}
                        />
                        <span className="text-white font-medium">
                          {level.label}
                        </span>
                      </div>
                      <div className="flex items-center gap-3">
                        <span className="text-white font-bold">
                          {level.count}
                        </span>
                        <div className="w-16 bg-white/10 rounded-full h-2">
                          <div
                            className={`h-2 rounded-full ${level.color}`}
                            style={{
                              width: `${
                                (level.count / team.totalMembers) * 100
                              }%`,
                            }}
                          />
                        </div>
                        <span className="text-xs text-slate-400 w-10 text-right">
                          {((level.count / team.totalMembers) * 100).toFixed(0)}
                          %
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
                <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                  <Target className="h-5 w-5 text-purple-400" />
                  Métriques clés
                </h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                    <span className="text-slate-300">
                      Couverture des compétences
                    </span>
                    <span className="text-white font-bold">
                      {team.skillCoverage.toFixed(1)}%
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                    <span className="text-slate-300">Compétences fortes</span>
                    <span className="text-white font-bold">
                      {teamInsights.strongSkills}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                    <span className="text-slate-300">
                      Objectifs d'apprentissage
                    </span>
                    <span className="text-white font-bold">
                      {teamInsights.totalLearners}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                    <span className="text-slate-300">Mentors disponibles</span>
                    <span className="text-white font-bold">
                      {skillAnalysis.reduce(
                        (sum, skill) =>
                          sum + skill.experts.filter((e) => e.canMentor).length,
                        0
                      )}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </TabsContent>

          {/* Onglet Compétences */}
          <TabsContent value="skills" className="space-y-6">
            {/* Filtres par catégorie */}
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-4">
              <div className="flex flex-wrap gap-2">
                <Button
                  variant={selectedCategory === "all" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setSelectedCategory("all")}
                  className={
                    selectedCategory === "all"
                      ? "bg-blue-500 text-white"
                      : "text-slate-400 hover:text-white hover:bg-white/10"
                  }
                >
                  Toutes ({skillAnalysis.length})
                </Button>
                {categories.map((category) => (
                  <Button
                    key={category}
                    variant={
                      selectedCategory === category ? "default" : "ghost"
                    }
                    size="sm"
                    onClick={() => setSelectedCategory(category)}
                    className={
                      selectedCategory === category
                        ? "bg-blue-500 text-white"
                        : "text-slate-400 hover:text-white hover:bg-white/10"
                    }
                  >
                    {category} (
                    {
                      skillAnalysis.filter((s) => s.category === category)
                        .length
                    }
                    )
                  </Button>
                ))}
              </div>
            </div>

            {/* Liste des compétences détaillée */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {filteredSkills.map((skill, idx) => (
                <div
                  key={idx}
                  className="bg-white/5 border border-white/10 rounded-xl p-4 hover:bg-white/10 transition-colors"
                >
                  <div className="flex items-center justify-between mb-3">
                    <div>
                      <h4 className="font-medium text-white">
                        {skill.skillName}
                      </h4>
                      <p className="text-xs text-slate-400">{skill.category}</p>
                    </div>
                    <div
                      className={`px-2 py-1 border rounded-lg text-center ${getSkillLevelBadgeClasses(
                        skill.averageLevel
                      )}`}
                    >
                      <span className="text-xs font-medium">
                        {getSkillLevelLabel(skill.averageLevel)}
                      </span>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-slate-300">
                        Niveau moyen:
                      </span>
                      <span className="text-white font-semibold">
                        {skill.averageLevel.toFixed(1)}/3
                      </span>
                    </div>

                    <div className="w-full bg-white/10 rounded-full h-2">
                      <div
                        className={`h-2 rounded-full transition-all ${getSkillLevelColor(
                          skill.averageLevel
                        )
                          .replace("bg-", "bg-gradient-to-r from-")
                          .replace("-500", "-500 to-")
                          .replace("500 to-", "400")}`}
                        style={{ width: `${(skill.averageLevel / 3) * 100}%` }}
                      />
                    </div>

                    <div className="grid grid-cols-3 gap-2 text-xs">
                      <div className="text-center">
                        <div className="text-white font-semibold">
                          {skill.totalEvaluations}
                        </div>
                        <div className="text-slate-400">Évaluations</div>
                      </div>
                      <div className="text-center">
                        <div className="text-green-300 font-semibold">
                          {skill.expertCount}
                        </div>
                        <div className="text-slate-400">Experts</div>
                      </div>
                      <div className="text-center">
                        <div className="text-blue-300 font-semibold">
                          {skill.learnerCount}
                        </div>
                        <div className="text-slate-400">Apprenants</div>
                      </div>
                    </div>

                    {skill.experts.filter((e) => e.canMentor).length > 0 && (
                      <div className="pt-2 border-t border-white/10">
                        <div className="text-xs text-slate-400 mb-1">
                          Mentors disponibles:
                        </div>
                        <div className="flex flex-wrap gap-1">
                          {skill.experts
                            .filter((e) => e.canMentor)
                            .slice(0, 2)
                            .map((expert, i) => (
                              <Badge
                                key={i}
                                variant="outline"
                                className="text-xs text-green-300 border-green-500/30"
                              >
                                {expert.name}
                              </Badge>
                            ))}
                          {skill.experts.filter((e) => e.canMentor).length >
                            2 && (
                            <Badge
                              variant="outline"
                              className="text-xs text-slate-400 border-slate-500/30"
                            >
                              +
                              {skill.experts.filter((e) => e.canMentor).length -
                                2}
                            </Badge>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </TabsContent>

          {/* Onglet Membres */}
          <TabsContent value="members" className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {team.members.map((member) => {
                const memberAvg =
                  member.skills.reduce((sum, skill) => sum + skill.level, 0) /
                  member.skills.length;
                const expertSkills = member.skills.filter(
                  (s) => s.level >= 2 && s.canMentor
                ).length;
                const learningGoals = member.skills.filter(
                  (s) => s.wantsToLearn
                ).length;

                return (
                  <div
                    key={member.uuid}
                    className="bg-white/5 border border-white/10 rounded-xl p-4 hover:bg-white/10 transition-colors cursor-pointer group"
                    onClick={() => {
                      setSelectedMember(member);
                      setIsMemberModalOpen(true);
                    }}
                  >
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-3">
                        <div className="p-2 bg-blue-500/20 border border-blue-500/30 rounded-xl">
                          <User className="h-4 w-4 text-blue-400" />
                        </div>
                        <div>
                          <div className="font-medium text-white group-hover:text-blue-300 transition-colors">
                            {member.firstName} {member.lastName}
                          </div>
                          <div className="text-sm text-slate-400">
                            {new Date(member.joinDate).toLocaleDateString()}
                          </div>
                        </div>
                      </div>
                      <div
                        className={`px-2 py-1 border rounded-lg ${getSkillLevelBadgeClasses(
                          memberAvg
                        )}`}
                      >
                        <span className="text-xs font-medium">
                          {getSkillLevelLabel(memberAvg)}
                        </span>
                      </div>
                    </div>

                    <div className="space-y-3">
                      <div className="flex items-center justify-between text-sm">
                        <span className="text-slate-300">Niveau moyen:</span>
                        <span className="text-white font-semibold">
                          {memberAvg.toFixed(1)}/3
                        </span>
                      </div>

                      <div className="w-full bg-white/10 rounded-full h-2">
                        <div
                          className={`h-2 rounded-full transition-all ${getSkillLevelColor(
                            memberAvg
                          )
                            .replace("bg-", "bg-gradient-to-r from-")
                            .replace("-500", "-400")}`}
                          style={{ width: `${(memberAvg / 3) * 100}%` }}
                        />
                      </div>

                      <div className="grid grid-cols-3 gap-2 text-xs">
                        <div className="text-center">
                          <div className="text-white font-semibold">
                            {member.skills.length}
                          </div>
                          <div className="text-slate-400">Compétences</div>
                        </div>
                        <div className="text-center">
                          <div className="text-green-300 font-semibold">
                            {expertSkills}
                          </div>
                          <div className="text-slate-400">Expertises</div>
                        </div>
                        <div className="text-center">
                          <div className="text-blue-300 font-semibold">
                            {learningGoals}
                          </div>
                          <div className="text-slate-400">Objectifs</div>
                        </div>
                      </div>

                      {expertSkills > 0 && (
                        <div className="flex items-center gap-2 text-xs">
                          <Award className="h-3 w-3 text-green-400" />
                          <span className="text-green-300">
                            Peut mentorer {expertSkills} compétence
                            {expertSkills > 1 ? "s" : ""}
                          </span>
                        </div>
                      )}

                      {learningGoals > 0 && (
                        <div className="flex items-center gap-2 text-xs">
                          <BookOpen className="h-3 w-3 text-blue-400" />
                          <span className="text-blue-300">
                            Souhaite apprendre {learningGoals} compétence
                            {learningGoals > 1 ? "s" : ""}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </TabsContent>

          {/* Onglet Insights */}
          <TabsContent value="insights" className="space-y-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Compétences à développer */}
              <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
                <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                  <TrendingUp className="h-5 w-5 text-red-400" />
                  Compétences à développer
                </h3>
                <div className="space-y-3">
                  {skillAnalysis
                    .filter((s) => s.averageLevel < 1.5)
                    .slice(0, 5)
                    .map((skill, idx) => (
                      <div
                        key={idx}
                        className="flex items-center justify-between p-3 bg-white/5 rounded-lg"
                      >
                        <div>
                          <div className="text-white font-medium">
                            {skill.skillName}
                          </div>
                          <div className="text-xs text-slate-400">
                            {skill.category}
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="text-red-300 font-semibold">
                            {skill.averageLevel.toFixed(1)}
                          </div>
                          <div className="text-xs text-slate-400">
                            {skill.learnerCount} intéressés
                          </div>
                        </div>
                      </div>
                    ))}
                </div>
              </div>

              {/* Opportunités de mentorat */}
              <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
                <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                  <MessageSquare className="h-5 w-5 text-green-400" />
                  Opportunités de mentorat
                </h3>
                <div className="space-y-3">
                  {skillAnalysis
                    .filter(
                      (s) =>
                        s.experts.filter((e) => e.canMentor).length > 0 &&
                        s.learnerCount > 0
                    )
                    .slice(0, 5)
                    .map((skill, idx) => (
                      <div key={idx} className="p-3 bg-white/5 rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <div className="text-white font-medium">
                            {skill.skillName}
                          </div>
                          <div className="text-xs text-slate-400">
                            {skill.category}
                          </div>
                        </div>
                        <div className="flex items-center justify-between text-xs">
                          <div className="text-green-300">
                            {skill.experts.filter((e) => e.canMentor).length}{" "}
                            mentor
                            {skill.experts.filter((e) => e.canMentor).length > 1
                              ? "s"
                              : ""}
                          </div>
                          <div className="text-blue-300">
                            {skill.learnerCount} apprenant
                            {skill.learnerCount > 1 ? "s" : ""}
                          </div>
                        </div>
                      </div>
                    ))}
                </div>
              </div>
            </div>

            {/* Recommandations */}
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Lightbulb className="h-5 w-5 text-yellow-400" />
                Recommandations pour l'équipe
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="p-4 bg-blue-500/10 border border-blue-500/20 rounded-xl">
                  <h4 className="font-medium text-blue-300 mb-2">
                    🎯 Formations prioritaires
                  </h4>
                  <p className="text-sm text-slate-300">
                    Organiser des formations sur{" "}
                    {skillAnalysis
                      .filter((s) => s.averageLevel < 1.5)
                      .slice(0, 2)
                      .map((s) => s.skillName)
                      .join(" et ")}
                    pour combler les lacunes identifiées.
                  </p>
                </div>

                <div className="p-4 bg-green-500/10 border border-green-500/20 rounded-xl">
                  <h4 className="font-medium text-green-300 mb-2">
                    🤝 Programme de mentorat
                  </h4>
                  <p className="text-sm text-slate-300">
                    Mettre en place un système de mentorat avec{" "}
                    {skillAnalysis.reduce(
                      (sum, skill) =>
                        sum + skill.experts.filter((e) => e.canMentor).length,
                      0
                    )}{" "}
                    mentors disponibles.
                  </p>
                </div>

                <div className="p-4 bg-purple-500/10 border border-purple-500/20 rounded-xl">
                  <h4 className="font-medium text-purple-300 mb-2">
                    📈 Capitaliser sur les forces
                  </h4>
                  <p className="text-sm text-slate-300">
                    Exploiter l'expertise en{" "}
                    {skillAnalysis
                      .filter((s) => s.averageLevel >= 2.5)
                      .slice(0, 2)
                      .map((s) => s.skillName)
                      .join(" et ")}
                    pour des projets ambitieux.
                  </p>
                </div>

                <div className="p-4 bg-orange-500/10 border border-orange-500/20 rounded-xl">
                  <h4 className="font-medium text-orange-300 mb-2">
                    🔄 Plan de développement
                  </h4>
                  <p className="text-sm text-slate-300">
                    Créer des parcours de montée en compétences personnalisés
                    pour {teamInsights.totalLearners} objectifs d'apprentissage.
                  </p>
                </div>
              </div>
            </div>
          </TabsContent>
        </Tabs>

        {/* Modal détail membre */}
        <Dialog open={isMemberModalOpen} onOpenChange={setIsMemberModalOpen}>
          <DialogContent className="max-w-4xl bg-slate-900/95 border-white/20 text-white max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center justify-between">
                {selectedMember && (
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-blue-500/20 border border-blue-500/30 rounded-xl">
                      <User className="h-5 w-5 text-blue-400" />
                    </div>
                    <div>
                      <span className="text-xl">
                        {selectedMember.firstName} {selectedMember.lastName}
                      </span>
                      <p className="text-sm text-slate-400 font-normal">
                        Membre depuis le{" "}
                        {new Date(selectedMember.joinDate).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                )}
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsMemberModalOpen(false)}
                  className="text-slate-400 hover:text-white"
                >
                  <X className="h-4 w-4" />
                </Button>
              </DialogTitle>
            </DialogHeader>

            {selectedMember && (
              <div className="space-y-6">
                {/* Stats du membre */}
                <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 évaluées
                    </div>
                  </div>
                  <div className="bg-white/5 border border-white/10 rounded-xl p-4 text-center">
                    <div className="text-2xl font-bold text-green-300">
                      {
                        selectedMember.skills.filter(
                          (s) => s.level >= 2 && s.canMentor
                        ).length
                      }
                    </div>
                    <div className="text-sm text-slate-400">Peut mentorer</div>
                  </div>
                  <div className="bg-white/5 border border-white/10 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-slate-400">
                      Souhaite apprendre
                    </div>
                  </div>
                </div>

                {/* Compétences détaillées */}
                <div>
                  <h4 className="font-medium mb-4 text-lg">
                    Portfolio de compétences
                  </h4>
                  <div className="space-y-2 max-h-96 overflow-y-auto">
                    {selectedMember.skills
                      .sort((a, b) => b.level - a.level)
                      .map((skill, idx) => (
                        <div
                          key={idx}
                          className="flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-colors"
                        >
                          <div className="flex-1">
                            <div className="flex items-center justify-between mb-2">
                              <div>
                                <div className="font-medium text-white">
                                  {skill.skillName}
                                </div>
                                <div className="text-sm text-slate-400">
                                  {skill.category}
                                </div>
                              </div>
                              <div
                                className={`px-2 py-1 border rounded-lg text-center ${getSkillLevelBadgeClasses(
                                  skill.level
                                )}`}
                              >
                                <span className="text-xs font-medium">
                                  {getSkillLevelLabel(skill.level)}
                                </span>
                              </div>
                            </div>

                            <div className="w-full bg-white/10 rounded-full h-2 mb-2">
                              <div
                                className={`h-2 rounded-full transition-all ${getSkillLevelColor(
                                  skill.level
                                )
                                  .replace("bg-", "bg-gradient-to-r from-")
                                  .replace("-500", "-400")}`}
                                style={{ width: `${(skill.level / 3) * 100}%` }}
                              />
                            </div>

                            <div className="flex items-center gap-2">
                              {skill.canMentor && (
                                <Badge
                                  variant="outline"
                                  className="text-xs text-green-300 border-green-500/30"
                                >
                                  <Award className="h-3 w-3 mr-1" />
                                  Mentor
                                </Badge>
                              )}
                              {skill.wantsToLearn && (
                                <Badge
                                  variant="outline"
                                  className="text-xs text-blue-300 border-blue-500/30"
                                >
                                  <BookOpen className="h-3 w-3 mr-1" />
                                  Apprenant
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>
                      ))}
                  </div>
                </div>
              </div>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}
