"use client";

import React, { createContext, useContext, useState, ReactNode } from 'react';
import { User } from '../types';
import { useRouter, usePathname } from 'next/navigation';

interface UserContextType {
    user: User | null;
    settings: any | null;
    login: (user: User) => void;
    logout: () => void;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export function UserProvider({ children }: { children: ReactNode }) {
    const [user, setUser] = useState<User | null>(null);
    const [settings, setSettings] = useState<any>(null);
    const router = useRouter();
    const pathname = usePathname();

    React.useEffect(() => {
        const savedUser = localStorage.getItem('afro_user');
        if (savedUser) {
            setUser(JSON.parse(savedUser));
        }

        // Fetch settings
        fetch('/api/settings')
            .then(res => res.json())
            .then(data => setSettings(data))
            .catch(err => console.error('Error fetching settings:', err));
    }, []);

    // Global suspension check
    React.useEffect(() => {
        if (user?.isSuspended && pathname !== '/suspended') {
            router.push('/suspended');
        }
    }, [user, pathname, router]);

    const login = (userData: User) => {
        setUser(userData);
        localStorage.setItem('afro_user', JSON.stringify(userData));
    };

    const logout = () => {
        setUser(null);
        localStorage.removeItem('afro_user');
    };

    return (
        <UserContext.Provider value={{ user, settings, login, logout }}>
            {children}
        </UserContext.Provider>
    );
}

export function useUser() {
    const context = useContext(UserContext);
    if (context === undefined) {
        throw new Error('useUser must be used within a UserProvider');
    }
    return context;
}
