import { useEffect, useState } from "react";
import useFetchUser from "../utils/fetchUser";
import CenteredContainer from "./ChildrenContainer";
import type { User } from "../types";

const processAttendance = (attendance: boolean | null): string => {
    if (attendance == null) {
        return "Пока не ответил"
    }
    return (attendance == true) ? "Да!" : "Не в этот раз"
}

function AttendanceTable() {

    const {getAttendanceAll} = useFetchUser()
    const [userAttendanceData, setUserAttendnaceData] = useState<User[]>([])

    const fetchUserData = async () => {
        const userData = await getAttendanceAll()
        setUserAttendnaceData(userData)
    }

    const handleRefresh = () => {
        fetchUserData()
    }

    useEffect(() => {
        fetchUserData()
    }, [])

    return (
        <>
            <CenteredContainer>
                <h2>Кто празднует?</h2>
                {userAttendanceData && (
                    <div className="table-wrapper">
                        <table>
                            <thead>
                                <tr>
                                    <th>Пятка</th>
                                    <th>Празднует с нами?</th>
                                </tr>
                            </thead>
                            <tbody>
                                {userAttendanceData && userAttendanceData.map((item) => (
                                    <tr>
                                        <td>{item.name}</td>
                                        <td>{processAttendance(item.attendance)}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                        <p className="scroll-instruction">Таблицу можно скроллить</p>
                    </div>
                )}
                <br/>
                <button onClick={handleRefresh}>Обновить</button>
            </CenteredContainer>
        </>
    )
}

export default AttendanceTable;