'use client';

import { User, UserRoleEnum } from '@/data/user/user.model';
import { user_requests } from '@/data/user/user.requests';
import { auth_service } from '@/services/auth';
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';

const initialState = {
    isAuth: false,
    isLoading: true,
    user: null,
};

type AuthContextType = {
    isAuth: boolean;
    isLoading: boolean;
    user: User | null;
    login: ({ accessToken }: { accessToken: string }) => Promise<void>;
    logout: () => void;
    refetchUserData: () => void;
    isAdmin: boolean;
    isAdminOrUzbek: boolean;
};

export const AuthContext = createContext<AuthContextType>(null!);

export const AuthContextProvider = (props: { children: React.ReactNode }) => {
    const [state, setState] = useState<{ isAuth: boolean; isLoading: boolean; user: User | null }>(() => {
        if (auth_service.getToken()) {
            return {
                ...initialState,
                isAuth: true,
            };
        } else {
            return initialState;
        }
    });
    const initialize = async () => {
        const _token = auth_service.getToken();

        if (_token) {
            try {
                const response = await user_requests.getMe();
                setState({
                    isAuth: true,
                    isLoading: false,
                    user: response.data.data,
                    //  || {
                    //     active: true,
                    //     id: 9999,
                    //     role: UserRoleEnum.CHINA_WORKER,
                    //     username: 'demo_username',
                    //     address: 'Demo Address',
                    //     fullName: 'FullDemoName',
                    //     phone: '99894444444444444',
                    // },
                });
            } catch (err) {
                console.error(err);
                setState({
                    isAuth: true,
                    isLoading: false,
                    user: null,
                });
            }
        } else {
            setState({
                isAuth: false,
                isLoading: false,
                user: null,
            });
        }
    };

    useEffect(() => {
        initialize();
    }, []);

    const login = async ({ accessToken }: { accessToken: string }) => {
        auth_service.login(accessToken);
        setState(prev => ({ ...prev, isLoading: true }));
        initialize();
    };

    const logout = () => {
        auth_service.logout();
    };

    const refetchUserData = useCallback(() => {
        initialize();
    }, []);

    return (
        <AuthContext.Provider
            value={{
                ...state,
                login,
                logout,
                refetchUserData,
                isAdmin: Boolean(state.user?.role.includes(UserRoleEnum.ADMIN)),
                isAdminOrUzbek: Boolean(
                    state.user?.role.includes(UserRoleEnum.ADMIN) || state.user?.role.includes(UserRoleEnum.UZB_WORKER)
                ),
            }}
        >
            {props.children}
        </AuthContext.Provider>
    );
};

export const AuthConsumer = AuthContext.Consumer;

export const useAuthContext = () => useContext(AuthContext);
