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

interface AuthProviderProps {
    children: React.ReactNode;
}

const DEFAULT_ORGANIZATION_ID = 'e47e6210-4879-4e5b-bf21-9285d2713123';
const DEFAULT_ORGANIZATION_NAME = 'Organização Padrão';

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

    useEffect(() => {
        const storedUser = localStorage.getItem('gpi_user');
        if (storedUser) {
            try {
                setAppUser(JSON.parse(storedUser));
            } catch (e) {
                console.error("Error parsing stored user", e);
            }
        }
        
        setApiOrganizationId(DEFAULT_ORGANIZATION_ID, DEFAULT_ORGANIZATION_NAME);
        setIsLoading(false);
    }, []);

    const signInWithPassword = async (password: string): Promise<boolean> => {
        try {
            const response = await api.post('/users/login', { password });
            if (response.data.success) {
                const adminUser = response.data.user as AppUser;
                setAppUser(adminUser);
                localStorage.setItem('gpi_user', JSON.stringify(adminUser));
                localStorage.setItem('gpi_token', response.data.token);
                return true;
            }
        } catch (error) {
            console.error("Login failed:", error);
        }
        return false;
    };

    const isDeveloper = useCallback(() => appUser?.email === 'admtracksteel@gmail.com' || appUser?.id === 'admin-user', [appUser]);
    const isAdmin = useCallback(() => appUser?.role === 'admin' || appUser?.email === 'admtracksteel@gmail.com', [appUser]);
    const isUser = useCallback(() => !!appUser, [appUser]);
    const isGuest = useCallback(() => !appUser, [appUser]);
    const canEdit = useCallback(() => isAdmin(), [isAdmin]);
    const refetchUser = useCallback(async () => {}, []);

    const value = useMemo(() => ({
        appUser,
        isLoading,
        isSignedIn: !!appUser,
        error: null,
        isAdmin,
        isUser,
        isGuest,
        isDeveloper,
        canEdit,
        refetchUser,
        signInWithPassword
    }), [appUser, isLoading, isAdmin, isUser, isGuest, isDeveloper, canEdit, refetchUser]);

    return (
        <AuthContext.Provider value={value}>
            {children}
        </AuthContext.Provider>
    );
};