import Context from './Context';
import CryptoJS from 'crypto-js';

import cookies from 'js-cookie';

import { useEffect, useState } from 'react';
import { requestAuth } from '../config/UserRequest.jsx';
import { requestGetAllCategory } from '../config/category';
import { ToastContainer, toast } from 'react-toastify';
import { getWebsite, topDeposit } from '../config/website';
import { useSocket } from '../hooks/useSocket';

export function Provider({ children }) {
    const [dataUser, setDataUser] = useState({});
    const [dataCategory, setDataCategory] = useState([]);
    const [dataWebsite, setDataWebsite] = useState({
        nameWebsite: '',
        logo: '',
        favicon: '',
        description: '',
        keywords: '',
        author: '',
        contact: '',
        social: '',
        status: '',
        banner: [],
    });
    const [dataTopDeposit, setDataTopDeposit] = useState([]);

    const fetchCategory = async () => {
        const res = await requestGetAllCategory();
        setDataCategory(res.metadata);
    };

    const fetchTopDeposit = async () => {
        const res = await topDeposit();
        setDataTopDeposit(res.metadata);
    };

    const fetchAuth = async () => {
        try {
            const res = await requestAuth();
            if (res.metadata) {
                setDataUser(res.metadata);
            }
        } catch (error) {
            console.error('Auth error:', error);
        }
    };

    const fetchWebsite = async () => {
        try {
            const response = await getWebsite();
            const data = response?.metadata;
            if (data) {
                setDataWebsite(data);
                if (data.nameWebsite) document.title = data.nameWebsite;
                if (data.favicon) {
                    const link = document.querySelector("link[rel='icon']") || document.createElement('link');
                    link.rel = 'icon';
                    link.type = 'image/png';
                    link.href = data.favicon;
                    document.getElementsByTagName('head')[0].appendChild(link);
                }
            }
        } catch (error) {
            console.error('fetchWebsite error:', error);
        }
    };

    useEffect(() => {
        fetchCategory();
        fetchWebsite();
        fetchTopDeposit();
        const token = cookies.get('logged');

        if (!token) {
            return;
        }
        fetchAuth();
    }, []);

    // Lắng nghe socket real-time khi admin cộng tiền
    useSocket(dataUser?._id ? String(dataUser._id) : null, {
        balance_updated: (data) => {
            // Cập nhật số dư trong state
            setDataUser((prev) => ({ ...prev, balance: data.newBalance }));

            // Hiển thị toast thông báo
            toast.success(
                `💰 ${data.message}`,
                {
                    position: 'top-right',
                    autoClose: 5000,
                    hideProgressBar: false,
                    closeOnClick: true,
                    pauseOnHover: true,
                    draggable: true,
                    style: {
                        background: 'linear-gradient(135deg, #22c55e, #16a34a)',
                        color: 'white',
                        fontWeight: 600,
                        borderRadius: '12px',
                    },
                }
            );
        },
    });

    return (
        <Context.Provider
            value={{
                dataUser,
                fetchAuth,
                dataCategory,
                fetchCategory,
                dataWebsite,
                dataTopDeposit,
                setDataUser,
            }}
        >
            {children}
            <ToastContainer />
        </Context.Provider>
    );
}

