"use client";

import React from "react";
import { useRouter } from "next/navigation";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Users, ExternalLink, Download, Eye } from "lucide-react";

import { TeamMember } from "@/lib/admin-types";

interface TeamDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  team: {
    teamId: string;
    teamName: string;
    direction: string;
    totalMembers: number;
    averageSkillLevel: number;
    topSkills: Array<{
      skillName: string;
      averageLevel: number;
      icon?: string;
    }>;
    skillCoverage: number;
    members: TeamMember[];
  } | null;
}

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

export function TeamDetailModal({
  isOpen,
  onClose,
  team,
}: TeamDetailModalProps) {
  const router = useRouter();

  if (!team) return null;

  const handleViewFullDetails = () => {
    router.push(`/admin/team/${team.teamId}`);
    onClose();
  };

  const handleExportReport = () => {
    // Rapport simple depuis la modale
    const reportData = {
      team: team.teamName,
      direction: team.direction,
      exportDate: new Date().toLocaleDateString(),
      summary: {
        totalMembers: team.totalMembers,
        averageSkillLevel: team.averageSkillLevel,
        skillCoverage: team.skillCoverage,
      },
      topSkills: team.topSkills,
    };

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

    const exportFileDefaultName = `apercu-${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 (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl bg-slate-800 border-white/20 text-white">
        <DialogHeader>
          <DialogTitle 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>
              <h2 className="text-xl font-bold">Équipe {team.teamName}</h2>
              <p className="text-sm text-slate-400">
                {team.direction} • {team.totalMembers} membres
              </p>
            </div>
          </DialogTitle>
          <DialogDescription className="text-slate-400">
            Aperçu rapide de l'équipe. Cliquez sur "Voir tous les détails" pour
            une vue complète.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* Stats générales */}
          <div className="grid grid-cols-3 gap-4">
            <div className="bg-white/5 border border-white/10 rounded-xl p-4 text-center">
              <Users className="h-6 w-6 text-green-400 mx-auto mb-2" />
              <div className="text-2xl font-bold text-white">
                {team.totalMembers}
              </div>
              <div className="text-xs text-slate-400">Membres</div>
            </div>
            <div className="bg-white/5 border border-white/10 rounded-xl p-4 text-center">
              <Eye className="h-6 w-6 text-blue-400 mx-auto mb-2" />
              <div className="text-2xl font-bold text-white">
                {((team.averageSkillLevel / 3) * 100).toFixed(0)}%
              </div>
              <div className="text-xs text-slate-400">Niveau moyen</div>
            </div>
            <div className="bg-white/5 border border-white/10 rounded-xl p-4 text-center">
              <ExternalLink className="h-6 w-6 text-orange-400 mx-auto mb-2" />
              <div className="text-2xl font-bold text-white">
                {team.skillCoverage.toFixed(0)}%
              </div>
              <div className="text-xs text-slate-400">Couverture</div>
            </div>
          </div>

          {/* Top compétences résumé */}
          <div className="bg-white/5 border border-white/10 rounded-xl p-4">
            <h3 className="font-medium text-white mb-3">Top 3 Compétences</h3>
            <div className="space-y-2">
              {team.topSkills.slice(0, 3).map((skill, idx) => (
                <div
                  key={idx}
                  className="flex items-center justify-between p-2 bg-white/5 rounded-lg"
                >
                  <span className="text-white text-sm">{skill.skillName}</span>
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-slate-400">
                      {((skill.averageLevel / 3) * 100).toFixed(0)}%
                    </span>
                    <div
                      className={`w-2 h-2 rounded-full ${getSkillLevelColor(
                        skill.averageLevel
                      )}`}
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-4 border-t border-white/10">
            <Button
              onClick={handleViewFullDetails}
              className="flex-1 bg-blue-500 hover:bg-blue-600 text-white"
            >
              <ExternalLink className="h-4 w-4 mr-2" />
              Voir tous les détails
            </Button>
            <Button
              onClick={handleExportReport}
              variant="outline"
              className="bg-white/5 border-white/20 text-white hover:bg-white/10"
            >
              <Download className="h-4 w-4 mr-2" />
              Aperçu
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
