import React, { useState, useEffect } from "react";
import Button from "../ui/button/button";
import styles from "./PendingMembers.module.css";

import getUserToValidate from "../../utils/users/getUserToValidate";
import getUserById from "../../utils/users/getUserById";
import validateUser from "../../utils/users/validateUser";
import deleteUser from "../../utils/users/deleteUser";

function PendingMembers() {
  const [pendingMembers, setPendingMembers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchPendingMembers = async () => {
      setLoading(true);
      const userIds = await getUserToValidate();
      if (userIds && userIds.length > 0) {
        const users = await Promise.all(userIds.map((id) => getUserById(id)));
        setPendingMembers(users.filter(Boolean));
      } else {
        setPendingMembers([]);
      }
      setLoading(false);
    };
    fetchPendingMembers();
  }, []);

  const removeMember = (id) => {
    setPendingMembers(prevMembers =>
      prevMembers.filter(member => member.id !== id)
    );
  };

  const handleValidate = async (id) => {
    setActionLoading(id);
    setError(null);
    try {
      const result = await validateUser(id);
      if (result.success) {
        removeMember(id);
      } else {
        setError(result.message || "Échec de la validation.");
      }
    } catch (err) {
      setError("Erreur lors de la validation.");
    } finally {
      setActionLoading(null);
    }
  };

  const handleReject = async (id) => {
    setActionLoading(id);
    setError(null);
    try {
      const result = await deleteUser(id);
      if (result.success) {
        removeMember(id);
      } else {
        setError(result.message || "Échec de la suppression.");
      }
    } catch (err) {
      setError("Erreur lors de la suppression.");
    } finally {
      setActionLoading(null);
    }
  };

  if (loading) {
    return <div>Chargement des membres en attente...</div>;
  }

  return (
    <div className={`${styles.rightBlock} glassCard`}>
      <h2>Membres en attente de validation</h2>
      {error && <p style={{ color: "red" }}>{error}</p>}

      <div className={styles.membersContainer}>
        {pendingMembers.length === 0 && <p>Aucun membre en attente</p>}

        {pendingMembers.map((member) => (
          <div key={member.id} className={`glassCard ${styles.memberCard}`}>
            <p>{member.name} {member.lastname}</p>
            <div className={styles.buttonGroup}>
              <Button
                onClick={() => handleValidate(member.id)}
                variant="primary"
                disabled={actionLoading === member.id}
              >
                {actionLoading === member.id ? "En cours..." : "Valider"}
              </Button>
              <Button
                onClick={() => handleReject(member.id)}
                variant="danger"
                disabled={actionLoading === member.id}
              >
                {actionLoading === member.id ? "En cours..." : "Refuser"}
              </Button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default PendingMembers;
