'use client';

import Tasks from '@/components/tasks/Tasks';
import { useCallback } from 'react';
import { StatusTask } from '@/interfaces/task.type';
import { usePlayerStore } from '@/store/player.state';
import { useTokenStore } from '@/store/token.state';
import { PlayerApi } from '@/api/player.api';

const TasksContainer = () => {
    const { player, setPlayer } = usePlayerStore();
    const { token } = useTokenStore();

    const handleClaimPrize = useCallback(
        async (taskId: number) => {
            if (!token) {
                return;
            }
            const playerApi = PlayerApi.getInstance(token);
            const updatedPlayer = await playerApi.updateTasks(player!.id, {
                taskId: taskId,
                status: 'claimed' as StatusTask,
            });
            const newPlayer = await playerApi.findPlayerByAuthId(
                encodeURIComponent(updatedPlayer.attributes.auth_id),
            );
            setPlayer(newPlayer);
        },
        [player, token],
    );

    const handleOpenLink = useCallback(
        async (link: string, taskId: number) => {
            if (!token) {
                return;
            }
            window.Telegram.WebApp.openLink(link);
            const playerApi = PlayerApi.getInstance(token);
            const updatedPlayer = await playerApi.updateTasks(player!.id, {
                taskId: taskId,
                status: 'pending_prize' as StatusTask,
            });
            const newPlayer = await playerApi.findPlayerByAuthId(
                encodeURIComponent(updatedPlayer.attributes.auth_id),
            );
            setPlayer(newPlayer);
        },
        [player, token],
    );

    return <Tasks handleClaimPrize={handleClaimPrize} handleOpenLink={handleOpenLink} />;
};

export default TasksContainer;
