import { useEffect, useState } from "react";
import styles from "./VolunteersPage.module.css";
import VolunteerCard from "./components/VolunteersCard/VolunteerCard";
import getAllUser from "../../utils/users/getAllUsers";
import ToolBar from "../../components/ToolBar/ToolBar";
import filter from "../../utils/filter";
import getUserById from "../../utils/users/getUserById";
import User from "./interfaces/user.interface";
import Loading from "../../components/ui/loading/loading";

interface Filters {
    alphabetical: "asc" | "desc";
    yearOrder: "asc" | "desc";
}

const VolunteerPage: React.FC = () => {
    const [filters, setFilters] = useState<Filters>({
        alphabetical: "asc",
        yearOrder: "desc",
    });

    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState<boolean>(true);

    useEffect(() => {
        const fetchUsers = async (): Promise<void> => {
            setLoading(true);

            try {
                const result = await getAllUser();

                if (result.status !== 200 || !Array.isArray(result.data)) {
                    console.error("Erreur lors du chargement des utilisateurs", result);
                    return;
                }

                const usersData = await Promise.all(
                    result.data.map(async (id: number): Promise<User | null> => {
                        const res = await getUserById(id);

                        if (res.status === 200) {
                            return res.data as User;
                        }

                        console.warn(`Utilisateur ${id} non récupéré`, res.status);
                        return null;
                    })
                );

                setUsers(usersData.filter((user): user is User => user !== null));
            } catch (error) {
                console.error("Erreur réseau", error);
            } finally {
                setLoading(false);
            }
        };

        fetchUsers();
    }, []);

    if(loading) return <Loading />;

    return (
        <div className={styles.container}>
            <ToolBar
                setFilters={setFilters}
                filters={filters}
                showCreate={false}
            />

            <div className={styles.usersList}>
                {filter(users, filters, "user").map((user: User) => (
                        <VolunteerCard key={user.id} user={user} />
                ))}
            </div>

        </div>
    );
};

export default VolunteerPage;
