"use client";

import { useState } from "react";
import { Team, SkillCategory } from "@/lib/types";
import { TeamStats, DirectionStats } from "@/services/admin-service";
import { TeamDetailModal } from "../team-detail/team-detail-modal";
import { AdminHeader } from "../utils/admin-header";
import { AdminOverviewCards } from "./admin-overview-cards";
import { AdminFilters } from "../utils/admin-filters";
import { AdminContentTabs } from "./admin-content-tabs";

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;

    // Filtrer les équipes avec 0 membres
    filtered = filtered.filter((team) => team.totalMembers > 0);

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

  // 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 */}
        <AdminHeader />

        {/* Overview Cards */}
        <AdminOverviewCards
          teams={teams}
          skillCategories={skillCategories}
          teamStats={teamStats}
          directionStats={directionStats}
          selectedDirections={selectedDirections}
          selectedTeams={selectedTeams}
          getFilteredTeamStats={getFilteredTeamStats}
          getFilteredDirectionStats={getFilteredDirectionStats}
        />

        {/* Filtres */}
        <AdminFilters
          teams={teams}
          teamStats={teamStats}
          selectedDirections={selectedDirections}
          selectedTeams={selectedTeams}
          onDirectionsChange={setSelectedDirections}
          onTeamsChange={setSelectedTeams}
          getFilteredTeamStats={getFilteredTeamStats}
        />

        {/* Main Content Tabs */}
        <AdminContentTabs
          getFilteredDirectionStats={getFilteredDirectionStats}
          getFilteredTeamStats={getFilteredTeamStats}
          onViewTeamDetails={handleViewTeamDetails}
          onExportTeamReport={handleExportTeamReport}
        />

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