import React, { createContext, useState, useEffect, ReactNode, useContext } from 'react';
import { checkLogin as apiCheckLogin, login as apiLogin, logout as apiLogout } from '@_api/auth/authAPI';
import type { LoginRequest, LoginCheckResponse } from '@_api/auth/authTypes';

interface AuthContextType {
    loggedIn: boolean;
    userName: string | null;
    role: 'ADMIN' | 'MEMBER' | null;
    loading: boolean; // Add loading state to type
    login: (data: LoginRequest) => Promise<LoginCheckResponse>;
    logout: () => Promise<void>;
    checkLogin: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [loggedIn, setLoggedIn] = useState(false);
    const [userName, setUserName] = useState<string | null>(null);
    const [role, setRole] = useState<'ADMIN' | 'MEMBER' | null>(null);
    const [loading, setLoading] = useState(true); // Add loading state

    const checkLogin = async () => {
        try {
            const response = await apiCheckLogin();
            setLoggedIn(true);
            setUserName(response.name);
            setRole(response.role);
        } catch (error) {
            setLoggedIn(false);
            setUserName(null);
            setRole(null);
            localStorage.removeItem('accessToken');
        } finally {
            setLoading(false); // Set loading to false after check is complete
        }
    };

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

    const login = async (data: LoginRequest) => {
        const response = await apiLogin(data);
        await checkLogin();
        return response;
    };

    const logout = async () => {
        try {
            await apiLogout();
        } finally {
            setLoggedIn(false);
            setUserName(null);
            setRole(null);
            localStorage.removeItem('accessToken');
        }
    };

    return (
        <AuthContext.Provider value={{ loggedIn, userName, role, loading, login, logout, checkLogin }}>
            {children}
        </AuthContext.Provider>
    );
};

export const useAuth = (): AuthContextType => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
};
