'use client';

import { FC, useCallback, useEffect, useRef, useState } from 'react';
import ModalExchange from '@/components/ui/modal-exchange/ModalExchange';
import { usePlayerStore } from '@/store/player.state';
import { useConfigStore } from '@/store/config.state';
import { useNotify } from '@/hooks/useNotify';
import { ExchangeRequestApi } from '@/api/exchange-request.api';
import { useModalStore } from '@/store/modal.state';
import { useTokenStore } from '@/store/token.state';
import { toFixed } from '@/utils/FormatNumber';

interface IModalExchangeContainer {
    isOpen: boolean;
    balance: number | undefined;
    onClose: () => void;
}

const ModalExchangeContainer: FC<IModalExchangeContainer> = ({ balance, isOpen, onClose }) => {
    const { token } = useTokenStore();

    const [amount, setAmount] = useState<number>(1);
    const [nickname, setNickname] = useState<string>('');
    const [isClosing, setIsClosing] = useState<boolean>(false);

    const rangeRef = useRef<HTMLInputElement>(null);

    const { player, setPlayer } = usePlayerStore();
    const { config } = useConfigStore();
    const { shopItemId, isDecimal, image, setShopItemId, setIsDecimal } = useModalStore();

    const { getSuccessNotify, getErrorNotifyByCount, getErrorNotifyByNickname } = useNotify();

    useEffect(() => {
        if (rangeRef.current) {
            rangeRef.current.style.setProperty('--value', amount.toString());
        }
    }, [amount]);

    useEffect(() => {
        if (isOpen) {
            setIsClosing(false);
            setAmount(0);
        }
    }, [isOpen]);

    const handleClose = () => {
        setIsClosing(true);
        setTimeout(() => {
            onClose();
        }, 500);
    };

    const handleCreateExchange = useCallback(
        async (amount: number, total: number, nickname: string) => {
            if (!token) {
                return;
            }
            const exchangeRequestApi = ExchangeRequestApi.getInstance(token);
            if (player && config) {
                if (nickname.length === 0) {
                    getErrorNotifyByNickname();
                } else if (total === 0) {
                    getErrorNotifyByCount();
                } else {
                    exchangeRequestApi
                        .createExchange({
                            amount: amount,
                            total: total,
                            playerId: player.id,
                            nickname: nickname,
                            balance: player.attributes.balance,
                            telegram_id: config.attributes.admins.data.map(
                                user => user.attributes.telegram_id,
                            ),
                            shop_item: shopItemId || undefined,
                            archive_request_id: player!.attributes.archive_request!.data?.id || -1,
                        })
                        .then(() => {
                            if (player) {
                                setPlayer({
                                    ...player,
                                    attributes: {
                                        ...player.attributes,
                                        balance: toFixed(player?.attributes.balance) - amount,
                                    },
                                });
                                setShopItemId(null);
                                setIsDecimal(true);
                            }
                        });
                    getSuccessNotify();
                    handleClose();
                }
            }
        },
        [player, token, shopItemId],
    );

    return (
        <ModalExchange
            isOpen={isOpen}
            isClosing={isClosing}
            balance={balance}
            amount={amount}
            nickname={nickname}
            rangeRef={rangeRef}
            onClose={handleClose}
            setNickname={setNickname}
            setAmount={setAmount}
            handleCreateExchange={handleCreateExchange}
        />
    );
};

export default ModalExchangeContainer;
