import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { supabase } from '../lib/supabase';
import { User } from '../types';

interface UserContextType {
    user: User | null;
    loading: boolean;
    isAdminView: boolean;
    isProfessionalView: boolean;
    isCompletingProfile: boolean;
    toggleAdminView: () => void;
    setIsProfessionalView: (isPro: boolean) => void;
    logout: () => Promise<void>;
    refreshProfile: () => Promise<void>;
}

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

export const UserProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);
    const [isAdminView, setIsAdminView] = useState(false);
    const [isProfessionalView, setIsProfessionalView] = useState(false);
    const [isCompletingProfile, setIsCompletingProfile] = useState(false);

    const fetchUserProfile = async (userId: string, email?: string) => {
        try {
            const { data: profile, error } = await supabase
                .from('profiles')
                .select('*')
                .eq('id', userId)
                .maybeSingle();

            if (error) throw error;

            if (!profile || !profile.phone_e164) {
                console.warn("UserContext: Perfil incompleto.");
                setIsCompletingProfile(true);
                // Mantemos user null ou parcial? App.tsx usava null para triggerar modal na landing
                // Vamos setar null para garantir que caia na landing, mas com flag isCompletingProfile true
                setUser(null);
                return;
            }

            setIsCompletingProfile(false);

            // Fetch Entitlements
            const { data: entitlement } = await supabase
                .from('user_entitlements')
                .select('*')
                .eq('user_id', userId)
                .maybeSingle();

            let plan: 'free' | 'pro' | 'trial' = 'free';
            if (entitlement?.is_active) {
                const code = entitlement.entitlement_code;
                if (['pro', 'mensal', 'trimestral', 'anual'].includes(code)) plan = 'pro';
                else if (code === 'trial') plan = 'trial';
            }

            const userData: User = {
                id: userId,
                name: profile.full_name || 'Usuário',
                email: email || profile.email || '',
                phone: profile.phone_e164,
                public_id: profile.public_id,
                is_admin: profile.is_admin,
                is_professional: profile.is_professional,
                plan: plan,
                plan_valid_until: entitlement?.valid_until
            };

            setUser(userData);

            // Auto-switch view logic
            if (profile.is_professional) {
                setIsProfessionalView(true);
            }

        } catch (error) {
            console.error('UserContext: Erro ao carregar perfil', error);
            setUser(null);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        let mounted = true;

        const handleSession = async (session: any) => {
            if (session?.user) {
                await fetchUserProfile(session.user.id, session.user.email);
            } else {
                setUser(null);
                setLoading(false);
            }
        };

        const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
            console.log(`UserContext Auth Event: ${event}`);
            if (!mounted) return;

            if (event === 'INITIAL_SESSION') {
                await handleSession(session);
            } else if (event === 'SIGNED_IN' || event === 'TOKEN_REFRESHED') {
                await handleSession(session);
            } else if (event === 'SIGNED_OUT') {
                setUser(null);
                setIsAdminView(false);
                setIsProfessionalView(false);
                setIsCompletingProfile(false);
                setLoading(false);
            }
        });

        // Initialize session manually in case INITIAL_SESSION doesn't trigger
        // (sometimes needed depending on supabase-js version and local storage state)
        supabase.auth.getSession().then(({ data: { session }, error }) => {
            if (error) {
                console.error("UserContext: Falha na sessão inicial", error);
                if (mounted) setLoading(false);
            } else if (!session) {
                // Se não há sessão e onAuthStateChange não disparou INITIAL_SESSION
                if (mounted) setLoading(false);
            }
        });

        return () => {
            mounted = false;
            subscription.unsubscribe();
        };
    }, []);

    const logout = async () => {
        await supabase.auth.signOut();
        // State updates handled by onAuthStateChange
    };

    const toggleAdminView = () => {
        if (user?.is_admin) setIsAdminView(prev => !prev);
    };

    const refreshProfile = async () => {
        const { data: { session } } = await supabase.auth.getSession();
        if (session?.user) {
            await fetchUserProfile(session.user.id, session.user.email);
        }
    };

    return (
        <UserContext.Provider value={{
            user,
            loading,
            isAdminView,
            isProfessionalView,
            isCompletingProfile,
            toggleAdminView,
            setIsProfessionalView,
            logout,
            refreshProfile
        }}>
            {children}
        </UserContext.Provider>
    );
};

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