'use client';

import { useCallback, useEffect, useState } from 'react';
import Home from '@/components/home/Home';
import { FormatTime } from '@/utils/FormatTime';
import { useButtonStore } from '@/store/button.state';
import { PlayerApi } from '@/api/player.api';
import { usePlayerStore } from '@/store/player.state';
import { useConfigStore } from '@/store/config.state';
import { useTokenStore } from '@/store/token.state';
import { toFixed } from '@/utils/FormatNumber';

const HomeContainer = () => {
    const { typeButton, setTypeButton } = useButtonStore();

    const { player: playerStore, setPlayer } = usePlayerStore();
    const { config: configStore } = useConfigStore();
    const { token } = useTokenStore();

    const [isLoading, setIsLoading] = useState<boolean>(true);
    const [remainingTime, setRemainingTime] = useState<number | null>(null);

    useEffect(() => {
        if (isLoading) {
            setIsLoading(false);
        }
    }, [isLoading]);

    useEffect(() => {
        if (playerStore && playerStore.attributes.start_farm && configStore) {
            const farmingTime = configStore.attributes.farming_time * 1000;
            const endTime = new Date(playerStore.attributes.start_farm).getTime() + farmingTime;

            const updateRemainingTime = () => {
                const now = new Date().getTime();
                const timeLeft = endTime - now;
                setRemainingTime(timeLeft > 0 ? timeLeft : 0);
            };

            updateRemainingTime();
            const interval = setInterval(updateRemainingTime, 1000);

            return () => clearInterval(interval);
        } else {
            setRemainingTime(null);
        }
    }, [playerStore, configStore]);

    useEffect(() => {
        if (!remainingTime && !playerStore?.attributes.start_farm) {
            setTypeButton('pending');
        } else if (remainingTime && playerStore?.attributes.start_farm) {
            setTypeButton('farming');
        } else if (!remainingTime && playerStore?.attributes.start_farm) {
            setTypeButton('claim_reward');
        }
    }, [remainingTime, playerStore]);

    const handleStartFarming = useCallback(async () => {
        if (!token || !playerStore) {
            return;
        }
        const api = PlayerApi.getInstance(token);
        const updatedPlayer = await api.startFarm(new Date(), playerStore.id);
        setPlayer(updatedPlayer);
    }, [playerStore]);

    const handleClaimRewards = useCallback(async () => {
        if (!token || !playerStore || !configStore) {
            return;
        }
        const api = PlayerApi.getInstance(token);
        // TODO: улучшить безопасность в методе claimRewards
        const updatedPlayer = await api.claimRewards(
            playerStore.id,
            toFixed(playerStore?.attributes.balance) + configStore?.attributes.farm_amount,
        );
        setPlayer(updatedPlayer);
    }, [playerStore, configStore]);

    return (
        <Home
            config={configStore}
            isLoading={isLoading}
            typeButton={typeButton}
            remainingTime={FormatTime(remainingTime)}
            handleStartFarming={handleStartFarming}
            handleClaimRewards={handleClaimRewards}
        />
    );
};

export default HomeContainer;
