import { createContext, useContext, useEffect, useState, ReactNode } from "react";
import { supabase } from "@/integrations/supabase/client";
import { User, Session } from "@supabase/supabase-js";

const REMEMBER_ME_KEY = 'appforge_remember_me';

interface AuthContextType {
  user: User | null;
  session: Session | null;
  loading: boolean;
  signUp: (email: string, password: string, displayName?: string) => Promise<{ error: Error | null }>;
  signIn: (email: string, password: string, rememberMe?: boolean) => Promise<{ error: Error | null }>;
  signInWithGoogle: () => Promise<{ error: Error | null }>;
  signInWithMagicLink: (email: string) => Promise<{ error: Error | null }>;
  resendVerificationEmail: (email: string) => Promise<{ error: Error | null }>;
  signOut: () => Promise<void>;
  resetPassword: (email: string) => Promise<{ error: Error | null }>;
}

const defaultAuthContext: AuthContextType = {
  user: null,
  session: null,
  loading: false,
  signUp: async () => ({ error: new Error("AuthProvider is not mounted") }),
  signIn: async () => ({ error: new Error("AuthProvider is not mounted") }),
  signInWithGoogle: async () => ({ error: new Error("AuthProvider is not mounted") }),
  signInWithMagicLink: async () => ({ error: new Error("AuthProvider is not mounted") }),
  resendVerificationEmail: async () => ({ error: new Error("AuthProvider is not mounted") }),
  signOut: async () => {
    throw new Error("AuthProvider is not mounted");
  },
  resetPassword: async () => ({ error: new Error("AuthProvider is not mounted") }),
};

const AuthContext = createContext<AuthContextType>(defaultAuthContext);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === defaultAuthContext) {
    console.error("useAuth called outside AuthProvider");
  }
  return context;
};

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Check if user should be remembered
    const checkRememberMe = () => {
      const rememberMe = localStorage.getItem(REMEMBER_ME_KEY);
      // If rememberMe is explicitly set to 'false' and this is a new browser session
      if (rememberMe === 'false') {
        const sessionActive = sessionStorage.getItem('session_active');
        if (!sessionActive) {
          // This is a new browser session and user didn't want to be remembered
          supabase.auth.signOut();
          return true;
        }
      }
      return false;
    };

    // Set up auth state listener FIRST
    const { data: { subscription } } = supabase.auth.onAuthStateChange(
      (event, session) => {
        if (session) {
          // Mark session as active for this browser session
          sessionStorage.setItem('session_active', 'true');
        }
        setSession(session);
        setUser(session?.user ?? null);
        setLoading(false);
      }
    );

    // THEN check for existing session
    supabase.auth.getSession().then(({ data: { session } }) => {
      // Check remember me preference before setting session
      if (session && checkRememberMe()) {
        setSession(null);
        setUser(null);
        setLoading(false);
        return;
      }
      
      if (session) {
        sessionStorage.setItem('session_active', 'true');
      }
      setSession(session);
      setUser(session?.user ?? null);
      setLoading(false);
    });

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

  const signUp = async (email: string, password: string, displayName?: string) => {
    try {
      const redirectUrl = `${window.location.origin}/`;
      
      const { error } = await supabase.auth.signUp({
        email,
        password,
        options: {
          emailRedirectTo: redirectUrl,
          data: {
            display_name: displayName || email.split('@')[0],
          },
        },
      });
      
      if (error) {
        let errorMessage = 'Failed to create account';
        if (error.message.includes('already registered')) {
          errorMessage = 'An account with this email already exists';
        } else if (error.message.includes('password')) {
          errorMessage = 'Password should be at least 6 characters';
        } else if (error.message.includes('email')) {
          errorMessage = 'Invalid email address';
        } else {
          errorMessage = error.message;
        }
        return { error: new Error(errorMessage) };
      }
      
      return { error: null };
    } catch (error) {
      return { error: error instanceof Error ? error : new Error('Failed to create account') };
    }
  };

  const signIn = async (email: string, password: string, rememberMe: boolean = true) => {
    try {
      const { error } = await supabase.auth.signInWithPassword({
        email,
        password,
      });
      
      if (error) {
        let errorMessage = 'Failed to sign in';
        if (error.message.includes('Invalid login credentials')) {
          errorMessage = 'Invalid email or password';
        } else if (error.message.includes('Email not confirmed')) {
          errorMessage = 'Please verify your email address';
        } else {
          errorMessage = error.message;
        }
        return { error: new Error(errorMessage) };
      }
      
      // Store remember me preference
      localStorage.setItem(REMEMBER_ME_KEY, rememberMe.toString());
      sessionStorage.setItem('session_active', 'true');
      
      return { error: null };
    } catch (error) {
      return { error: error instanceof Error ? error : new Error('Failed to sign in') };
    }
  };

  const signInWithGoogle = async () => {
    try {
      const { error } = await supabase.auth.signInWithOAuth({
        provider: 'google',
        options: {
          redirectTo: `${window.location.origin}/dashboard`,
        },
      });
      
      if (error) {
        return { error: new Error(error.message) };
      }
      
      return { error: null };
    } catch (error) {
      return { error: error instanceof Error ? error : new Error('Failed to sign in with Google') };
    }
  };

  const signInWithMagicLink = async (email: string) => {
    try {
      const { error } = await supabase.auth.signInWithOtp({
        email,
        options: {
          emailRedirectTo: `${window.location.origin}/dashboard`,
        },
      });
      
      if (error) {
        return { error: new Error(error.message) };
      }
      
      return { error: null };
    } catch (error) {
      return { error: error instanceof Error ? error : new Error('Failed to send magic link') };
    }
  };

  const resendVerificationEmail = async (email: string) => {
    try {
      const redirectUrl = `${window.location.origin}/`;
      
      const { error } = await supabase.auth.resend({
        type: 'signup',
        email,
        options: {
          emailRedirectTo: redirectUrl,
        },
      });
      
      if (error) {
        return { error: new Error(error.message) };
      }
      
      return { error: null };
    } catch (error) {
      return { error: error instanceof Error ? error : new Error('Failed to resend verification email') };
    }
  };

  const signOut = async () => {
    try {
      await supabase.auth.signOut();
      // Clear remember me and session tracking
      localStorage.removeItem(REMEMBER_ME_KEY);
      sessionStorage.removeItem('session_active');
      setUser(null);
      setSession(null);
    } catch (error) {
      console.error('Sign out error:', error);
    }
  };

  const resetPassword = async (email: string) => {
    try {
      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/auth?mode=reset`,
      });
      
      if (error) {
        return { error: new Error(error.message) };
      }
      
      return { error: null };
    } catch (error) {
      return { error: error instanceof Error ? error : new Error('Failed to send reset email') };
    }
  };

  return (
    <AuthContext.Provider value={{ 
      user, 
      session, 
      loading, 
      signUp, 
      signIn, 
      signInWithGoogle,
      signInWithMagicLink,
      resendVerificationEmail,
      signOut,
      resetPassword 
    }}>
      {children}
    </AuthContext.Provider>
  );
};
