import { useState, useEffect } from 'react';
import { getUserTasks } from '@/api/users.service';
import { Button } from '@/components/ui/button';

export default function Calendar() {
    const [tasksFromBackend, setTasksFromBackend] = useState([]);
    const [loading, setLoading] = useState(true);

    // Fetch tasks when component mounts
    useEffect(() => {
        const fetchTasks = async () => {
            try {
                console.log('Calendar: Fetching user tasks...');
                const response = await getUserTasks(1);
                console.log('Calendar: Tasks from backend:', response);
                setTasksFromBackend(response);
            } catch (error) {
                console.error('Calendar: Failed to fetch tasks:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchTasks();
    }, []);

    const today = new Date();
    const currentDay = today.getDay();


    const currentDate = new Date(today);
    const dayOffset = currentDay === 0 ? -6 : 1 - currentDay;
    currentDate.setDate(today.getDate() + dayOffset);


    const groupTasksByDay = (tasks) => {
        const grouped = {};

        tasks.forEach(task => {
            const taskDate = new Date(task.due_date);
            const dateKey = taskDate.toDateString();

            if (!grouped[dateKey]) {
                grouped[dateKey] = [];
            }

            grouped[dateKey].push({
                id: task.id,
                title: task.title,
                priority: task.priority,
                completed: task.status === 'closed' || task.status === 'completed',
                dueDate: task.due_date
            });
        });

        return grouped;
    };

    const groupedTasks = groupTasksByDay(tasksFromBackend);


    const daysOfWeek = [
        'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'
    ].map((name, index) => {
        const date = new Date(currentDate);
        date.setDate(currentDate.getDate() + index);
        const dateKey = date.toDateString();

        return {
            name,
            date: date.getDate(),
            month: date.toLocaleDateString('en-US', { month: 'short' }),
            fullDate: date,
            tasks: groupedTasks[dateKey] || []
        };
    });

    if (loading) {
        return (
            <div className="dashboard-surface-container">
                <div className="flex items-center justify-center p-8">
                    <p className="text-lg">Loading tasks...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="dashboard-surface-container">
            <div className="dashboard-week-grid">
                {daysOfWeek.map((day, index) => {
                    const isToday = day.fullDate.toDateString() === today.toDateString();

                    return (
                        <div
                            key={day.name}
                            className={`dashboard-day-column ${isToday ? 'today' : ''} dashboard-card-filled`}
                        >
                            <div className="dashboard-day-header">
                                <h3 className="dashboard-day-title">{day.name}</h3>
                                <p className="dashboard-day-date">{day.month} {day.date}</p>
                            </div>
                            <div className="dashboard-tasks-container">
                                {
                                    day.tasks.map((task) => (
                                        <div
                                            key={task.id}
                                            className={`dashboard-task-card ${task.completed ? 'completed' : ''} priority-${task.priority}`}
                                        >
                                            <div className="dashboard-task-header">
                                                <span className={`dashboard-task-priority ${task.priority}`}></span>
                                                <p className="dashboard-task-title">{task.title}</p>
                                            </div>
                                        </div>
                                    ))
                                }
                                <Button variant="outline" onClick={() => {
                                    console.log('Add task clicked');
                                }}>
                                    +
                                </Button>
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    )
}