import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Trash2, Eye, KeyRound } from "lucide-react";
import { useRouter } from "next/navigation";

interface ManagerTableProps {
  managers: any[];
  onDelete: (id: number) => void;
  onView: (id: number) => void;
}

export default function ManagerTable({ managers, onDelete, onView }: ManagerTableProps) {
  const router = useRouter();
  const [loading, setLoading] = useState<number | null>(null);

  const handleViewManager = (managerId: number) => {
    router.push(`/admin-dashboard/managers/${managerId}`);
  };

  const handleImpersonate = async (managerId: number, managerName: string) => {
    try {
      setLoading(managerId);
      const response = await fetch('/api/impersonate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: managerId }),
      });
      const data = await response.json();
      if (response.ok && data.success) {
        localStorage.setItem('impersonatedManagerId', managerId.toString());
        localStorage.setItem('impersonatedManagerName', managerName);
        alert(`Vous êtes maintenant connecté en tant que ${managerName}`);
        window.location.href = data.redirectUrl || `/`;
      } else {
        alert(data.error || "Erreur lors de l'usurpation d'identité.");
        setLoading(null);
      }
    } catch (e) {
      alert("Erreur réseau lors de l'usurpation d'identité.");
      setLoading(null);
    }
  };

  const handleResetPassword = async (managerId: number, managerName: string) => {
    try {
      setLoading(managerId);
      const response = await fetch('/api/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: managerId }),
      });
      const data = await response.json();
      if (response.ok && data.success) {
        alert(`✅ Mot de passe réinitialisé pour ${managerName} !\n\nNouveau mot de passe temporaire : ${data.tempPassword}\n\n⚠️ Transmettez ce mot de passe au manager pour qu'il puisse se reconnecter.`);
        setLoading(null);
      } else {
        alert(data.error || "Erreur lors de la réinitialisation du mot de passe.");
        setLoading(null);
      }
    } catch (e) {
      alert("Erreur réseau lors de la réinitialisation du mot de passe.");
      setLoading(null);
    }
  };

  return (
    <div className="overflow-x-auto">
      <table className="min-w-full divide-y divide-gray-200">
        <thead className="bg-gray-50">
          <tr>
            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nom</th>
            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Téléphone</th>
            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
          </tr>
        </thead>
        <tbody className="bg-white divide-y divide-gray-200">
          {managers.map((manager) => {
            const managerName = `${manager.firstName} ${manager.lastName}`;
            return (
              <tr key={manager.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <span 
                    className={`text-sm font-medium text-blue-700 underline cursor-pointer ${loading === manager.id ? 'opacity-50' : ''}`} 
                    onClick={() => !loading && handleViewManager(manager.id)}
                  >
                    {loading === manager.id ? 'Chargement...' : managerName}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className="text-sm text-gray-500">{manager.email}</span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className="text-sm text-gray-500">{manager.phone}</span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex gap-2">
                    <Button variant="ghost" size="icon" onClick={() => handleImpersonate(manager.id, managerName)} title="Se connecter en tant que ce manager"><Eye className="h-4 w-4" /></Button>
                    <Button variant="ghost" size="icon" onClick={() => onDelete(manager.id)}><Trash2 className="h-4 w-4 text-red-600" /></Button>
                    <Button variant="ghost" size="icon" title="Réinitialiser le mot de passe" onClick={() => handleResetPassword(manager.id, managerName)}><KeyRound className="h-4 w-4 text-orange-500" /></Button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}