"use client";

import { useState, useEffect } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { useSession } from "next-auth/react";
import { AddUserButton } from "./add-user-button";

interface User {
  id: string;
  username: string;
  firstName: string;
  lastName: string;
  email: string;
  createdTimestamp: number;
  roles: string[];
}

interface UsersTableProps {
  userRole: string[];
}

export function UsersTable({ userRole }: UsersTableProps) {
  const { data: session } = useSession();

  const [users, setUsers] = useState<User[]>([]);

  const handleAddUser = (newUser: User) => {
    console.log("Nouvel utilisateur:", newUser);
    console.log("Utilisateurs actuels:", users);
    setUsers((prevUsers) => [...prevUsers, newUser]);
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await fetch("/api/users");
      const data = await response.json();
      setUsers(data);
    } catch (error) {
      console.error("Erreur lors de la récupération des utilisateurs:", error);
    }
  };

  const canDelete = (targetUserRole: string[]) => {
    if (userRole.includes("admin")) return true;
    if (userRole.includes("TEACHERS")) {
      return targetUserRole.includes("STUDENTS");
    }
    return false;
  };

  const handleDelete = async (userId: string) => {
    try {
      await fetch(`/api/users/${userId}`, { method: "DELETE" });
      fetchUsers();
    } catch (error) {
      console.error("Erreur lors de la suppression:", error);
    }
  };

  const filterUsers = (users: User[]) => {
    if (userRole.includes("admin")) return users;
    if (userRole.includes("TEACHERS")) {
      return users.filter(
        (user) =>
          user.roles.includes("TEACHERS") || user.roles.includes("STUDENTS")
      );
    }
    return users.filter((user) => user.roles.includes("STUDENTS"));
  };

  if (!session) return null;

  return (
    <>
      <div className='flex justify-between items-center mb-6'>
        <h1 className='text-2xl font-bold'>Gestion des utilisateurs</h1>
        {(session.user.role.includes("admin") ||
          session.user.role.includes("TEACHERS")) && (
          <AddUserButton
            userRole={session.user.role}
            handleAddUser={handleAddUser}
          />
        )}
      </div>
      {users.length === 0 ? (
        <div className='text-center'>Chargement...</div>
      ) : (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Nom d'utilisateur</TableHead>
              <TableHead>Prénom</TableHead>
              <TableHead>Nom</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Date d'inscription</TableHead>
              <TableHead>Roles</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filterUsers(users).map((user) => (
              <TableRow key={user.id}>
                <TableCell>{user.username}</TableCell>
                <TableCell>{user.firstName}</TableCell>
                <TableCell>{user.lastName}</TableCell>
                <TableCell>{user.email}</TableCell>
                <TableCell>
                  {new Date(user.createdTimestamp).toLocaleDateString()}
                </TableCell>
                <TableCell>{user.roles.join(", ")}</TableCell>
                <TableCell>
                  {canDelete(user.roles) && (
                    <Button
                      variant='destructive'
                      size='sm'
                      onClick={() => handleDelete(user.id)}
                    >
                      Supprimer
                    </Button>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </>
  );
}
