"use client";

import { useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Users, Target, Building2, UserCheck, Filter } from "lucide-react";
import { Team, SkillCategory } from "@/lib/types";
import {
  TeamStatsCard,
  DirectionOverview,
  MultiSelectFilter,
} from "@/components/admin";
import { TeamDetailModal } from "@/components/admin/team-detail-modal";
import { TeamStats, DirectionStats } from "@/services/admin-service";

interface AdminClientWrapperProps {
  teams: Team[];
  skillCategories: SkillCategory[];
  teamStats: TeamStats[];
  directionStats: DirectionStats[];
}

export function AdminClientWrapper({
  teams,
  skillCategories,
  teamStats,
  directionStats,
}: AdminClientWrapperProps) {
  // 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);

  // 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();
  };

  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),
                  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>
  );
}
