"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";
import {
  Users,
  TrendingUp,
  BarChart3,
  Target,
  Building2,
  UserCheck,
  Filter,
} from "lucide-react";
import { loadTeams, loadSkillCategories } from "@/lib/data-loader";
import { Team, SkillCategory, UserEvaluation } from "@/lib/types";
import {
  TeamStatsCard,
  DirectionOverview,
  MultiSelectFilter,
} from "@/components/admin";
import { TeamDetailModal } from "@/components/admin/team-detail-modal";

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; // Percentage of skills evaluated
  members: TeamMember[];
}

interface DirectionStats {
  direction: string;
  teams: TeamStats[];
  totalMembers: number;
  averageSkillLevel: number;
  topCategories: Array<{ category: string; averageLevel: number }>;
}

// Helper function to generate realistic team members
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)];

    // Each member evaluates 8-15 random skills
    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), // 0-3
        canMentor: Math.random() > 0.7, // 30% chance
        wantsToLearn: Math.random() > 0.6, // 40% chance
      }));

    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], // Random date in last 3 years
    };
  });
}

// Helper function to get random skills from categories
function getRandomSkills(skillCategories: SkillCategory[], count: number = 3) {
  const allSkills: Array<{
    skillName: string;
    category: string;
    icon: string;
  }> = [];

  skillCategories.forEach((category) => {
    category.skills.forEach((skill) => {
      allSkills.push({
        skillName: skill.name,
        category: category.category,
        icon: skill.icon || "",
      });
    });
  });

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

  // Sort by average level (descending - highest first)
  return randomSkills.sort((a, b) => b.averageLevel - a.averageLevel);
}

// Mock data generator - à remplacer par de vraies données
function generateMockTeamStats(
  teams: Team[],
  skillCategories: SkillCategory[]
): TeamStats[] {
  return teams.map((team) => {
    const memberCount = Math.floor(Math.random() * 10) + 3; // 3-12 members
    const members = generateTeamMembers(
      team.name,
      memberCount,
      skillCategories
    );

    return {
      teamId: team.id,
      teamName: team.name,
      direction: team.direction,
      totalMembers: memberCount,
      averageSkillLevel: Math.random() * 3, // 0-3
      topSkills: getRandomSkills(skillCategories, 3),
      skillCoverage: Math.random() * 100, // 0-100%
      members: members,
    };
  });
}

function generateDirectionStats(teamStats: TeamStats[]): DirectionStats[] {
  const directions = Array.from(new Set(teamStats.map((t) => t.direction)));

  return directions.map((direction) => {
    const directionTeams = teamStats.filter((t) => t.direction === direction);
    const totalMembers = directionTeams.reduce(
      (sum, t) => sum + t.totalMembers,
      0
    );
    const averageSkillLevel =
      directionTeams.reduce((sum, t) => sum + t.averageSkillLevel, 0) /
      directionTeams.length;

    return {
      direction,
      teams: directionTeams,
      totalMembers,
      averageSkillLevel,
      topCategories: [
        { category: "Frontend", averageLevel: Math.random() * 3 },
        { category: "Backend", averageLevel: Math.random() * 3 },
        { category: "DevOps", averageLevel: Math.random() * 3 },
      ],
    };
  });
}

export default function AdminPage() {
  const [teams, setTeams] = useState<Team[]>([]);
  const [skillCategories, setSkillCategories] = useState<SkillCategory[]>([]);
  const [teamStats, setTeamStats] = useState<TeamStats[]>([]);
  const [directionStats, setDirectionStats] = useState<DirectionStats[]>([]);
  const [loading, setLoading] = useState(true);

  // Filtres
  const [selectedDirections, setSelectedDirections] = useState<string[]>([]);
  const [selectedTeams, setSelectedTeams] = useState<string[]>([]);

  // Modale de détails
  const [selectedTeamForModal, setSelectedTeamForModal] =
    useState<TeamStats | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

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

        setTeams(teamsData);
        setSkillCategories(categoriesData);

        // Generate mock stats
        const mockTeamStats = generateMockTeamStats(teamsData, categoriesData);
        const mockDirectionStats = generateDirectionStats(mockTeamStats);

        setTeamStats(mockTeamStats);
        setDirectionStats(mockDirectionStats);
      } catch (error) {
        console.error("Failed to load admin data:", error);
      } finally {
        setLoading(false);
      }
    }

    loadData();
  }, []);

  // Fonctions de filtrage
  const getFilteredTeamStats = () => {
    let filtered = teamStats;

    if (selectedDirections.length > 0) {
      filtered = filtered.filter((team) =>
        selectedDirections.includes(team.direction)
      );
    }

    if (selectedTeams.length > 0) {
      filtered = filtered.filter((team) => selectedTeams.includes(team.teamId));
    }

    return filtered;
  };

  const getFilteredDirectionStats = () => {
    let filtered = directionStats;

    if (selectedDirections.length > 0) {
      filtered = filtered.filter((direction) =>
        selectedDirections.includes(direction.direction)
      );
    }

    // Si des équipes spécifiques sont sélectionnées, filtrer aussi les équipes dans les directions
    if (selectedTeams.length > 0) {
      filtered = filtered
        .map((direction) => ({
          ...direction,
          teams: direction.teams.filter((team) =>
            selectedTeams.includes(team.teamId)
          ),
          totalMembers: direction.teams
            .filter((team) => selectedTeams.includes(team.teamId))
            .reduce((sum, team) => sum + team.totalMembers, 0),
          averageSkillLevel: direction.teams
            .filter((team) => selectedTeams.includes(team.teamId))
            .reduce(
              (sum, team, _, arr) => sum + team.averageSkillLevel / arr.length,
              0
            ),
        }))
        .filter((direction) => direction.teams.length > 0);
    }

    return filtered;
  };

  // Options pour les filtres
  const directionOptions = Array.from(
    new Set(teams.map((team) => team.direction))
  ).map((direction) => ({
    id: direction,
    label: direction,
    count: teams.filter((team) => team.direction === direction).length,
  }));

  const teamOptions = teams.map((team) => ({
    id: team.id,
    label: `${team.name} (${team.direction})`,
    count: teamStats.find((stat) => stat.teamId === team.id)?.totalMembers || 0,
  }));

  // Fonctions pour les actions des équipes
  const handleViewTeamDetails = (team: TeamStats) => {
    setSelectedTeamForModal(team);
    setIsModalOpen(true);
  };

  const handleExportTeamReport = (team: TeamStats) => {
    const reportData = {
      team: team.teamName,
      direction: team.direction,
      date: new Date().toLocaleDateString(),
      stats: {
        members: team.totalMembers,
        averageLevel: team.averageSkillLevel,
        coverage: team.skillCoverage,
      },
      topSkills: team.topSkills,
    };

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

    const exportFileDefaultName = `rapport-${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="container mx-auto p-6">
        <div className="flex items-center justify-center h-64">
          <div className="text-lg">
            Chargement des données d'administration...
          </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">
      {/* 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">
            <Building2 className="h-4 w-4 text-blue-400" />
            <span className="text-sm font-medium text-slate-200">
              Administration
            </span>
          </div>

          <h1 className="text-4xl font-bold text-white">
            Dashboard Managérial
          </h1>

          <p className="text-slate-400 max-w-2xl mx-auto leading-relaxed">
            Vue d'ensemble des compétences par équipe et direction pour pilotage
            stratégique
          </p>
        </div>

        {/* Overview Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 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 justify-between mb-4">
              <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 className="text-xs text-slate-400 font-medium">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? "FILTRÉES"
                  : "TOTAL"}
              </div>
            </div>
            <div className="space-y-1">
              <p className="text-2xl font-bold text-white">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? getFilteredTeamStats().length
                  : teams.length}
              </p>
              <p className="text-sm text-slate-400">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? "Équipes filtrées"
                  : "Équipes"}
              </p>
              {(selectedDirections.length > 0 || selectedTeams.length > 0) && (
                <p className="text-xs text-slate-500">
                  sur {teams.length} au total
                </p>
              )}
            </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 justify-between mb-4">
              <div className="p-2 bg-green-500/20 border border-green-500/30 rounded-xl">
                <UserCheck className="h-5 w-5 text-green-400" />
              </div>
              <div className="text-xs text-slate-400 font-medium">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? "FILTRÉS"
                  : "TOTAL"}
              </div>
            </div>
            <div className="space-y-1">
              <p className="text-2xl font-bold text-white">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? getFilteredTeamStats().reduce(
                      (sum, t) => sum + t.totalMembers,
                      0
                    )
                  : teamStats.reduce((sum, t) => sum + t.totalMembers, 0)}
              </p>
              <p className="text-sm text-slate-400">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? "Membres filtrés"
                  : "Membres"}
              </p>
              {(selectedDirections.length > 0 || selectedTeams.length > 0) && (
                <p className="text-xs text-slate-500">
                  sur {teamStats.reduce((sum, t) => sum + t.totalMembers, 0)} au
                  total
                </p>
              )}
            </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 justify-between mb-4">
              <div className="p-2 bg-purple-500/20 border border-purple-500/30 rounded-xl">
                <Building2 className="h-5 w-5 text-purple-400" />
              </div>
              <div className="text-xs text-slate-400 font-medium">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? "FILTRÉES"
                  : "TOTAL"}
              </div>
            </div>
            <div className="space-y-1">
              <p className="text-2xl font-bold text-white">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? getFilteredDirectionStats().length
                  : directionStats.length}
              </p>
              <p className="text-sm text-slate-400">
                {selectedDirections.length > 0 || selectedTeams.length > 0
                  ? "Directions filtrées"
                  : "Directions"}
              </p>
              {(selectedDirections.length > 0 || selectedTeams.length > 0) && (
                <p className="text-xs text-slate-500">
                  sur {directionStats.length} au total
                </p>
              )}
            </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 justify-between mb-4">
              <div className="p-2 bg-orange-500/20 border border-orange-500/30 rounded-xl">
                <Target className="h-5 w-5 text-orange-400" />
              </div>
              <div className="text-xs text-slate-400 font-medium">
                RÉFÉRENTIEL
              </div>
            </div>
            <div className="space-y-1">
              <p className="text-2xl font-bold text-white">
                {skillCategories.reduce(
                  (sum, cat) => sum + cat.skills.length,
                  0
                )}
              </p>
              <p className="text-sm text-slate-400">Compétences suivies</p>
              <p className="text-xs text-slate-500">
                {skillCategories.length} catégories
              </p>
            </div>
          </div>
        </div>

        {/* Filtres */}
        <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
          <div className="flex items-center gap-2 mb-6">
            <div className="p-2 bg-blue-500/20 border border-blue-500/30 rounded-xl">
              <Filter className="h-4 w-4 text-blue-400" />
            </div>
            <h3 className="text-lg font-semibold text-white">
              Filtres avancés
            </h3>
          </div>

          <div className="flex flex-col lg:flex-row gap-4">
            <div className="flex-1">
              <MultiSelectFilter
                title="Directions"
                options={directionOptions}
                selectedValues={selectedDirections}
                onChange={setSelectedDirections}
                placeholder="Toutes les directions"
                icon={<Building2 className="h-4 w-4" />}
              />
            </div>
            <div className="flex-1">
              <MultiSelectFilter
                title="Équipes"
                options={teamOptions}
                selectedValues={selectedTeams}
                onChange={setSelectedTeams}
                placeholder="Toutes les équipes"
                icon={<Users className="h-4 w-4" />}
              />
            </div>

            {/* Résumé des filtres actifs */}
            {(selectedDirections.length > 0 || selectedTeams.length > 0) && (
              <div className="flex flex-col lg:flex-row items-center gap-3">
                <div className="bg-blue-500/20 border border-blue-500/30 rounded-xl px-3 py-2">
                  <div className="flex items-center gap-2">
                    <Target className="h-3 w-3 text-blue-400" />
                    <span className="text-sm text-blue-300 font-medium">
                      {getFilteredTeamStats().reduce(
                        (sum, t) => sum + t.totalMembers,
                        0
                      )}{" "}
                      membres
                    </span>
                  </div>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setSelectedDirections([]);
                    setSelectedTeams([]);
                  }}
                  className="text-xs text-slate-400 hover:text-white hover:bg-white/10"
                >
                  Réinitialiser
                </Button>
              </div>
            )}
          </div>
        </div>

        {/* Main Content Tabs */}
        <Tabs defaultValue="directions" 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-2 bg-transparent border-0">
              <TabsTrigger
                value="directions"
                className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-slate-400 hover:text-white transition-colors"
              >
                Vue par Direction
              </TabsTrigger>
              <TabsTrigger
                value="teams"
                className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-slate-400 hover:text-white transition-colors"
              >
                Vue par Équipe
              </TabsTrigger>
            </TabsList>
          </div>

          <TabsContent value="directions" className="space-y-6">
            <div className="grid gap-6">
              {getFilteredDirectionStats().length > 0 ? (
                getFilteredDirectionStats().map((direction) => (
                  <DirectionOverview
                    key={direction.direction}
                    direction={direction.direction}
                    teams={direction.teams}
                    totalMembers={direction.totalMembers}
                    averageSkillLevel={direction.averageSkillLevel}
                    topCategories={direction.topCategories}
                    onViewTeamDetails={handleViewTeamDetails}
                    onExportTeamReport={handleExportTeamReport}
                  />
                ))
              ) : (
                <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-12 text-center">
                  <div className="p-3 bg-slate-500/20 border border-slate-500/30 rounded-xl w-fit mx-auto mb-4">
                    <Building2 className="h-6 w-6 text-slate-400" />
                  </div>
                  <h3 className="text-lg font-medium text-white mb-2">
                    Aucune direction trouvée
                  </h3>
                  <p className="text-slate-400 text-sm">
                    Aucune direction ne correspond aux filtres sélectionnés.
                  </p>
                </div>
              )}
            </div>
          </TabsContent>

          <TabsContent value="teams" className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {getFilteredTeamStats().length > 0 ? (
                getFilteredTeamStats().map((team) => (
                  <TeamStatsCard
                    key={team.teamId}
                    teamId={team.teamId}
                    teamName={team.teamName}
                    direction={team.direction}
                    totalMembers={team.totalMembers}
                    averageSkillLevel={team.averageSkillLevel}
                    topSkills={team.topSkills}
                    skillCoverage={team.skillCoverage}
                    onViewDetails={() => handleViewTeamDetails(team)}
                    onViewReport={() => handleExportTeamReport(team)}
                  />
                ))
              ) : (
                <div className="col-span-full">
                  <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-12 text-center">
                    <div className="p-3 bg-slate-500/20 border border-slate-500/30 rounded-xl w-fit mx-auto mb-4">
                      <Users className="h-6 w-6 text-slate-400" />
                    </div>
                    <h3 className="text-lg font-medium text-white mb-2">
                      Aucune équipe trouvée
                    </h3>
                    <p className="text-slate-400 text-sm">
                      Aucune équipe ne correspond aux filtres sélectionnés.
                    </p>
                  </div>
                </div>
              )}
            </div>
          </TabsContent>
        </Tabs>

        {/* Modale de détails d'équipe */}
        <TeamDetailModal
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          team={selectedTeamForModal}
        />
      </div>
    </div>
  );
}
