import { useEffect, useState } from "react";
import getEventById from "../../utils/events/getEventById.js";
import styles from "./Task.module.css";
import formatDate from "../../utils/date/formatDate";

interface TaskType {
    id: number;
    name: string;
    description: string;
    location: string;
    start: string;
    end: string;
    max_participants: number;
    events_id: number;
    created_at: string;
    updated_at: string;
    pivot: {
        user_id: number;
        task_id: number;
    };
}

interface EventType {
    id: number;
    name: string;
    description?: string;
    location?: string;
    start?: string;
    end?: string;
    created_at?: string;
    updated_at?: string;
}

interface TaskProps {
    task: TaskType;
}

const Task: React.FC<TaskProps> = ({ task }) => {
    const [event, setEvent] = useState<EventType | null>(null);

    useEffect(() => {
        const fetchEvent = async (): Promise<void> => {
            try {
                const e = await getEventById(task.events_id);
                setEvent(e.data as EventType);
            } catch (error) {
                console.error("Erreur lors du chargement de l'événement", error);
            }
        };

        fetchEvent();
    }, [task.events_id]);

    return (
        <div className={`${styles.task} glassCard`}>
            <div className={styles.content}>
                <div>
                    <h2>
                        {event?.name} - {task.name}
                    </h2>
                    <p className={styles.desc}>{task.description}</p>
                    <p className={styles.date}>
                        {formatDate(task.start)}
                    </p>
                </div>
            </div>
        </div>
    );
};

export default Task;