'use client';

import { ITask } from '@/api/tasks.api';
import { FC, useCallback } from 'react';
import styles from '@/components/tasks/Tasks.module.css';
import Image from 'next/image';
import { IFinishedTasks } from '@/interfaces/player.type';
import TaskContent from '@/components/tasks/TaskContent';

interface ITaskProps {
    task: ITask;
    finishedTask: IFinishedTasks | undefined;
    handleClaimPrize: (taskId: number, prize: number) => Promise<void>;
    handleOpenLink: (link: string, taskId: number) => Promise<void>;
}

const Task: FC<ITaskProps> = ({ task, finishedTask, handleClaimPrize, handleOpenLink }) => {
    const handleTaskFunction = useCallback(() => {
        if (!finishedTask) {
            return handleOpenLink(task.attributes.link, task.id);
        }
    }, [handleOpenLink, finishedTask]);

    return (
        <div
            className={
                finishedTask && finishedTask.attributes.status === 'claimed'
                    ? `${styles.taskClaimed} ${styles.task}`
                    : `${styles.task}`
            }
            onClick={handleTaskFunction}
        >
            {task?.attributes?.icon?.data && (
                <div className={styles.taskIcon}>
                    <Image
                        src={`${process.env.NEXT_PUBLIC_STRAPI || ''}${task.attributes.icon.data.attributes.url}`}
                        alt={'task icon'}
                        width={32}
                        height={32}
                    />
                </div>
            )}
            <div className={styles.taskContent}>
                <div
                    className={
                        finishedTask && finishedTask.attributes.status === 'claimed'
                            ? `${styles.taskClaimedTitle} ${styles.taskTitle}`
                            : `${styles.taskTitle}`
                    }
                >
                    <span>{task.attributes.title}</span>
                </div>
                <TaskContent
                    taskId={task.id}
                    link={task.attributes.link}
                    status={finishedTask?.attributes.status}
                    prize={task.attributes.prize}
                    handleClaimPrize={handleClaimPrize}
                />
            </div>
        </div>
    );
};

export default Task;
