import React, { useState, useEffect, useCallback } from 'react';
import type { AppUser } from '../types';
import { AuthContext } from './AuthContextType';
import api, { getBaseUrl, setApiOrganizationId } from '../services/api';

const API_URL = getBaseUrl();

interface AuthProviderProps {
    children: React.ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
    const [appUser, setAppUser] = useState<AppUser | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const logout = useCallback(() => {
        localStorage.removeItem('gpi_token');
        setAppUser(null);
        setApiOrganizationId(null);
        window.location.href = '/login';
    }, []);

    const fetchMe = useCallback(async () => {
        const token = localStorage.getItem('gpi_token');
        if (!token) {
            setAppUser(null);
            setIsLoading(false);
            return;
        }

        try {
            setIsLoading(true);
            const response = await api.get('/auth/me');
            const userData = response.data;
            
            setAppUser({
                ...userData,
                id: userData._id || userData.id
            });
            
            if (userData.organizationId) {
                setApiOrganizationId(userData.organizationId);
            }
        } catch (err: any) {
            console.error('Error fetching current user:', err);
            if (err.response?.status === 401) {
                logout();
            } else {
                setError('Erro ao carregar dados do usuário');
            }
        } finally {
            setIsLoading(false);
        }
    }, [logout]);

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

    const isDeveloper = useCallback(() => {
        return appUser?.email === 'admtracksteel@gmail.com';
    }, [appUser]);

    const isAdmin = useCallback(() => appUser?.role === 'admin' || isDeveloper(), [appUser, isDeveloper]);
    const isUser = useCallback(() => appUser?.role === 'user' || isAdmin(), [appUser, isAdmin]);
    const isGuest = useCallback(() => appUser?.role === 'guest' && !isDeveloper(), [appUser, isDeveloper]);
    const canEdit = useCallback(() => (appUser?.role !== 'guest' && appUser?.role !== undefined) || isDeveloper(), [appUser, isDeveloper]);

    return (
        <AuthContext.Provider
            value={{
                appUser,
                isLoading,
                isSignedIn: !!appUser,
                error,
                isAdmin,
                isUser,
                isGuest,
                isDeveloper,
                canEdit,
                refetchUser: fetchMe,
                logout, // Added logout to context
            }}
        >
            {children}
        </AuthContext.Provider>
    );
};
