import React from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '../lib/supabase';
import { User } from '@supabase/supabase-js';

export interface AuthContextType {
  user: User | null;
  loading: boolean;
  error: string | null;
  signIn: (email: string, password: string) => Promise<any>;
  signUp: (email: string, password: string) => Promise<any>;
  signOut: () => Promise<void>;
  userRole: string | null;
}

const AuthContext = React.createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const navigate = useNavigate();
  const [user, setUser] = React.useState<User | null>(null);
  const [userRole, setUserRole] = React.useState<string | null>(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const fetchSession = async () => {
      const { data: { session } } = await supabase.auth.getSession();
      console.log('Sessão atual:', session);
      
      if (session?.user) {
        setUser(session.user);
        const role = session.user.user_metadata.role;
        console.log('Role na sessão:', role);
        setUserRole(role);

        if (role === 'school') {
          navigate('/dashboard');
        }
      }
      setLoading(false);
    };

    fetchSession();

    const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
      console.log('Evento de auth:', event);
      console.log('Sessão no evento:', session);
      
      if (session?.user) {
        setUser(session.user);
        const role = session.user.user_metadata.role;
        console.log('Role no evento:', role);
        setUserRole(role);

        if (event === 'SIGNED_IN') {
          if (role === 'school') {
            navigate('/dashboard');
          }
        }
      } else {
        setUser(null);
        setUserRole(null);
        navigate('/');
      }
      
      setLoading(false);
    });

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

  const value: AuthContextType = {
    user,
    loading,
    error: null,
    signIn: async () => ({}),
    signUp: async () => ({}),
    signOut: async () => {
      await supabase.auth.signOut();
      setUser(null);
      setUserRole(null);
      navigate('/');
    },
    userRole
  };

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

export function useAuth() {
  const context = React.useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
} 