'use client';

import { PropsWithChildren, useEffect, useState } from 'react';
import { usePlayerStore } from '@/store/player.state';
import { ProvidersProps } from '@/components/providers/Providers';
import { useTokenStore } from '@/store/token.state';
import { PlayerApi } from '@/api/player.api';
import styles from './Providers.module.css';

export const PlayerProvider = ({
    children,
    id,
}: PropsWithChildren & Pick<ProvidersProps, 'id'>) => {
    const { player, setPlayer, isLoading, stopLoading } = usePlayerStore();
    const { token } = useTokenStore();
    const [username, setUsername] = useState('');

    useEffect(() => {
        if (!token) {
            console.log('[PlayerProvider] no token yet, waiting...');
            return;
        }
        console.log('[PlayerProvider] token received, loading player...');
        try {
            const tgUser = window.Telegram?.WebApp?.initDataUnsafe?.user;
            const username = String(tgUser?.username || 'unknown');
            console.log('[PlayerProvider] telegram username:', username, 'tgUser:', tgUser);
            setUsername(username);
        } catch (e) {
            console.error('[PlayerProvider] error getting telegram user:', e);
        }
        const playerApi = PlayerApi.getInstance(token);
        playerApi.findPlayerByAuthId(id).then(player => {
            console.log('[PlayerProvider] player loaded:', player?.id);
            setPlayer(player);
            stopLoading();
        }).catch(err => {
            console.error('[PlayerProvider] error loading player:', err);
            stopLoading();
        });
    }, [token]);

    if (isLoading) {
        return (
            <div className={styles.loading}>
                <span>Загрузка...</span>
            </div>
        );
    }
    if (!player) {
        return (
            <div className={styles.loading}>
                <span>
                    Что-то пошло не так... Попробуйте написать /start, чтобы получить актуальную
                    ссылку
                </span>
            </div>
        );
    }
    if (player.attributes.telegram_nick !== username) {
        return (
            <div className={styles.loading}>
                <span>
                    Похоже, что Вы изменили свой ID в Telegram, попробуйте написать /start, чтобы
                    получить актуальную ссылку
                </span>
            </div>
        );
    }

    return <>{children}</>;
};
