import { adminLogin as apiLogin, logout as apiLogout } from '@_api/auth/authAPI';
import {
    type AdminLoginSuccessResponse,
    type AdminType,
    type LoginRequest,
} from '@_api/auth/authTypes';
import React, { createContext, type ReactNode, useContext, useEffect, useState } from 'react';

interface AdminAuthContextType {
    isAdmin: boolean;
    name: string | null;
    type: AdminType | null;
    storeId: number | null;
    loading: boolean;
    login: (data: Omit<LoginRequest, 'principalType'>) => Promise<AdminLoginSuccessResponse>;
    logout: () => Promise<void>;
}

const AdminAuthContext = createContext<AdminAuthContextType | undefined>(undefined);

export const AdminAuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [isAdmin, setIsAdmin] = useState(false);
    const [name, setName] = useState<string | null>(null);
    const [type, setType] = useState<AdminType | null>(null);
    const [storeId, setStoreId] = useState<number | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        try {
            const token = localStorage.getItem('accessToken');
            const storedName = localStorage.getItem('adminName');
            const storedType = localStorage.getItem('adminType') as AdminType | null;
            const storedStoreId = localStorage.getItem('adminStoreId');

            if (token && storedName && storedType) {
                setIsAdmin(true);
                setName(storedName);
                setType(storedType);
                setStoreId(storedStoreId ? parseInt(storedStoreId, 10) : null);
            }
        } catch (error) {
            console.error("Failed to load admin auth state from storage", error);
        } finally {
            setLoading(false);
        }
    }, []);

    const login = async (data: Omit<LoginRequest, 'principalType'>) => {
        const response = await apiLogin(data);

        localStorage.setItem('accessToken', response.accessToken);
        localStorage.setItem('adminName', response.name);
        localStorage.setItem('adminType', response.type);
        if (response.storeId) {
            localStorage.setItem('adminStoreId', response.storeId.toString());
        } else {
            localStorage.removeItem('adminStoreId');
        }

        setIsAdmin(true);
        setName(response.name);
        setType(response.type);
        setStoreId(response.storeId);

        return response;
    };

    const logout = async () => {
        try {
            await apiLogout();
        } finally {
            localStorage.removeItem('accessToken');
            localStorage.removeItem('adminName');
            localStorage.removeItem('adminType');
            localStorage.removeItem('adminStoreId');
            setIsAdmin(false);
            setName(null);
            setType(null);
            setStoreId(null);
        }
    };

    return (
        <AdminAuthContext.Provider value={{ isAdmin, name, type, storeId, loading, login, logout }}>
            {children}
        </AdminAuthContext.Provider>
    );
};

export const useAdminAuth = (): AdminAuthContextType => {
    const context = useContext(AdminAuthContext);
    if (!context) {
        throw new Error('useAdminAuth must be used within an AdminAuthProvider');
    }
    return context;
};
