"use client";

import { useState, useEffect } from "react";
import { Users, User, Calendar, X, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { TeamMember } from "@/services/admin-management-service";
import { AdminManagementService } from "@/services/admin-management-service";
import { useToast } from "@/hooks/use-toast";

interface TeamMembersModalProps {
  teamId: string;
  teamName: string;
  isOpen: boolean;
  onClose: () => void;
  onMemberRemoved?: () => void; // Callback pour notifier le parent qu'un membre a été supprimé
}

export function TeamMembersModal({
  teamId,
  teamName,
  isOpen,
  onClose,
  onMemberRemoved,
}: TeamMembersModalProps) {
  const [members, setMembers] = useState<TeamMember[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deletingMemberId, setDeletingMemberId] = useState<string | null>(null);
  const { toast } = useToast();

  useEffect(() => {
    if (isOpen && teamId) {
      fetchMembers();
    }
  }, [isOpen, teamId]);

  const fetchMembers = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const membersData = await AdminManagementService.getTeamMembers(teamId);
      setMembers(membersData);
    } catch (err: any) {
      setError(err.message || "Erreur lors du chargement des membres");
    } finally {
      setIsLoading(false);
    }
  };

  const handleRemoveMember = async (memberId: string, memberName: string) => {
    if (
      !confirm(`Êtes-vous sûr de vouloir retirer ${memberName} de l'équipe ?`)
    ) {
      return;
    }

    setDeletingMemberId(memberId);
    try {
      await AdminManagementService.removeTeamMember(teamId, memberId);

      // Mettre à jour la liste locale
      setMembers((prev) => prev.filter((member) => member.id !== memberId));

      // Notifier le parent qu'un membre a été supprimé
      onMemberRemoved?.();

      toast({
        title: "Succès",
        description: `${memberName} a été retiré de l'équipe`,
      });
    } catch (err: any) {
      toast({
        title: "Erreur",
        description: err.message || "Erreur lors de la suppression du membre",
        variant: "destructive",
      });
    } finally {
      setDeletingMemberId(null);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <Card className="w-full max-w-2xl max-h-[80vh] overflow-hidden">
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
          <div className="flex items-center gap-3">
            <Users className="w-6 h-6 text-blue-400" />
            <div>
              <CardTitle className="text-xl">Membres de l'équipe</CardTitle>
              <p className="text-sm text-slate-500 font-normal">{teamName}</p>
            </div>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            className="h-8 w-8 p-0"
          >
            <X className="w-4 h-4" />
          </Button>
        </CardHeader>

        <CardContent className="space-y-4">
          {isLoading ? (
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="flex items-center gap-3">
                  <Skeleton className="w-8 h-8 rounded-full" />
                  <div className="flex-1 space-y-2">
                    <Skeleton className="h-4 w-32" />
                    <Skeleton className="h-3 w-24" />
                  </div>
                </div>
              ))}
            </div>
          ) : error ? (
            <div className="text-center py-8">
              <div className="text-red-400 mb-2">
                <Users className="w-12 h-12 mx-auto" />
              </div>
              <p className="text-red-400 font-medium">{error}</p>
              <Button variant="outline" onClick={fetchMembers} className="mt-3">
                Réessayer
              </Button>
            </div>
          ) : members.length === 0 ? (
            <div className="text-center py-8">
              <div className="text-slate-400 mb-2">
                <Users className="w-12 h-12 mx-auto" />
              </div>
              <p className="text-slate-400 font-medium">
                Aucun membre dans cette équipe
              </p>
              <p className="text-slate-500 text-sm mt-1">
                Les membres apparaîtront ici une fois qu'ils seront assignés
              </p>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between mb-4">
                <Badge variant="outline" className="text-sm">
                  {members.length} membre{members.length > 1 ? "s" : ""}
                </Badge>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={fetchMembers}
                  className="text-xs"
                >
                  Actualiser
                </Button>
              </div>

              <div className="space-y-3 max-h-96 overflow-y-auto">
                {members.map((member) => (
                  <div
                    key={member.id}
                    className="flex items-center gap-3 p-3 rounded-lg border border-slate-200/10 bg-slate-50/5 hover:bg-slate-50/10 transition-colors"
                  >
                    <div className="w-8 h-8 rounded-full bg-blue-500/20 flex items-center justify-center">
                      <User className="w-4 h-4 text-blue-400" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-white truncate">
                        {member.fullName}
                      </p>
                      <div className="flex items-center gap-2 text-xs text-slate-400">
                        <Calendar className="w-3 h-3" />
                        <span>
                          Membre depuis{" "}
                          {new Date(member.joinedAt).toLocaleDateString(
                            "fr-FR",
                            {
                              year: "numeric",
                              month: "long",
                            }
                          )}
                        </span>
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() =>
                        handleRemoveMember(member.id, member.fullName)
                      }
                      disabled={deletingMemberId === member.id}
                      className="text-red-400 hover:text-red-300 hover:bg-red-500/20 h-6 w-6 p-0 shrink-0"
                      title="Retirer de l'équipe"
                    >
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </div>
                ))}
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
