'use client';

import { FC, useEffect, useRef, useState } from 'react';
import styles from '@/components/tasks/Tasks.module.css';
import Task from '@/components/tasks/Task';
import { useTasksStore } from '@/store/tasks.state';
import { usePlayerStore } from '@/store/player.state';

interface ITasksProps {
    handleClaimPrize: (taskId: number, prize: number) => Promise<void>;
    handleOpenLink: (link: string, taskId: number) => Promise<void>;
}

const Tasks: FC<ITasksProps> = ({ handleOpenLink, handleClaimPrize }) => {
    const tasksBlockRef = useRef<HTMLDivElement>(null);
    const [isOverflow, setIsOverflow] = useState(false);
    const { tasks } = useTasksStore();
    const { player } = usePlayerStore();

    useEffect(() => {
        const checkOverflow = () => {
            if (tasksBlockRef.current) {
                setIsOverflow(
                    tasksBlockRef.current.scrollHeight > tasksBlockRef.current.clientHeight,
                );
            }
        };

        checkOverflow();

        window.addEventListener('resize', checkOverflow);

        return () => window.removeEventListener('resize', checkOverflow);
    }, []);

    return (
        <div className={styles.tasks}>
            <div className={styles.tasksHeader}>
                <span>Задания</span>
            </div>
            <div
                className={`${styles.tasksBlock} ${isOverflow ? styles.overflow : ''}`}
                ref={tasksBlockRef}
            >
                {tasks.map(task => {
                    const finishedTask = player?.attributes.finished_tasks.data?.find(
                        el => el?.attributes.task?.data?.id === task?.id,
                    );
                    return (
                        <Task
                            key={task.id}
                            task={task}
                            finishedTask={finishedTask}
                            handleClaimPrize={handleClaimPrize}
                            handleOpenLink={handleOpenLink}
                        />
                    );
                })}
            </div>
        </div>
    );
};

export default Tasks;
