
import React, { createContext, useContext, useEffect, useState } from 'react';
import { supabase, isSupabaseConfigured } from '../lib/supabaseClient';
import { Session, User } from '@supabase/supabase-js';

interface AuthContextType {
  session: Session | null;
  user: User | null;
  loading: boolean;
  isAdmin: boolean;
  signOut: () => Promise<void>;
  refreshDemoUser: () => void;
}

const AuthContext = createContext<AuthContextType>({
  session: null,
  user: null,
  loading: true,
  isAdmin: false,
  signOut: async () => {},
  refreshDemoUser: () => {},
});

export const AuthProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
  const [session, setSession] = useState<Session | null>(null);
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);

  const loadDemoUser = () => {
    try {
      const stored = localStorage.getItem('demo_user_session');
      if (stored) {
        const parsed = JSON.parse(stored);
        setSession(parsed);
        setUser(parsed.user);
        setIsAdmin(parsed.user.email === 'motionstudiohq@gmail.com');
      } else {
        setSession(null);
        setUser(null);
        setIsAdmin(false);
      }
    } catch (e) {
      console.error('Error loading demo user', e);
    }
  };

  const checkAdminStatus = async (currentUser: User | null) => {
    if (!currentUser) {
      setIsAdmin(false);
      return;
    }

    // 1. Hardcoded Super Admin Check (Ez mindig működik, RLS-től függetlenül)
    if (currentUser.email === 'motionstudiohq@gmail.com') {
      setIsAdmin(true);
      return;
    }

    // 2. Database Role Check (Hibatűrő módon)
    if (isSupabaseConfigured) {
      try {
        const { data, error } = await supabase
          .from('roles')
          .select('role')
          .eq('id', currentUser.id)
          .maybeSingle();
        
        if (error) {
          console.warn('RLS Policy Error in AuthContext (recursion?):', error.message);
          return; // Ha hiba van, hagyatkozunk az email alapú ellenőrzésre
        }
        
        if (data?.role === 'admin') {
          setIsAdmin(true);
          return;
        }
      } catch (err) {
        console.error('Error checking admin role:', err);
      }
    }
    
    setIsAdmin(false);
  };

  useEffect(() => {
    const initAuth = async () => {
      if (!isSupabaseConfigured) {
        loadDemoUser();
        setLoading(false);
        return;
      }

      try {
        const { data, error } = await supabase.auth.getSession();
        if (error) throw error;
        
        const currentSession = data.session;
        setSession(currentSession);
        setUser(currentSession?.user ?? null);
        if (currentSession?.user) await checkAdminStatus(currentSession.user);
      } catch (err) {
        console.error('Auth initialization error:', err);
      } finally {
        setLoading(false);
      }

      const { data: listener } = supabase.auth.onAuthStateChange(async (_event, session) => {
        setSession(session);
        setUser(session?.user ?? null);
        if (session?.user) await checkAdminStatus(session.user);
        setLoading(false);
      });

      return () => {
        listener.subscription.unsubscribe();
      };
    };

    initAuth();
  }, []);

  const signOut = async () => {
    if (!isSupabaseConfigured) {
      localStorage.removeItem('demo_user_session');
      setSession(null);
      setUser(null);
      setIsAdmin(false);
      return;
    }
    try {
      await supabase.auth.signOut();
      setIsAdmin(false);
    } catch (error) {
      console.error('Error signing out:', error);
    }
  };

  const refreshDemoUser = () => {
    if (!isSupabaseConfigured) loadDemoUser();
  };

  return (
    <AuthContext.Provider value={{ session, user, loading, isAdmin, signOut, refreshDemoUser }}>
      {!loading && children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);
