import { createClient, type User } from '@supabase/supabase-js'
import { createContext, useContext, useEffect, useState } from 'react'

const supabase = createClient(
    import.meta.env.VITE_SUPABASE_URL,
    import.meta.env.VITE_SUPABASE_ANON_KEY,
)

export interface SupabaseAuthState {
    isAuthenticated: boolean
    user: any
    login: (email: string, password: string) => Promise<void>
    logout: () => Promise<void>
    isLoading: boolean
}

const SupabaseAuthContext = createContext<SupabaseAuthState | undefined>(
    undefined,
)

export function SupabaseAuthProvider({
    children,
}: {
    children: React.ReactNode
}) {
    const [user, setUser] = useState<User | null>(null)
    const [isAuthenticated, setIsAuthenticated] = useState(false)
    const [isLoading, setIsLoading] = useState(true)

    useEffect(() => {
        // Get initial session
        supabase.auth.getSession().then(({ data: { session } }) => {
            setUser(session?.user ?? null)
            setIsAuthenticated(!!session?.user)
            setIsLoading(false)
        })

        // Listen for auth changes
        const {
            data: { subscription },
        } = supabase.auth.onAuthStateChange((_event, session) => {
            setUser(session?.user ?? null)
            setIsAuthenticated(!!session?.user)
            setIsLoading(false)
        })

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

    const login = async (email: string, password: string) => {
        const { error } = await supabase.auth.signInWithPassword({
            email,
            password,
        })
        if (error?.code === 'invalid_credentials') throw new Error('Credenciales inválidas')
        else if (error) throw error
    }

    const logout = async () => {
        const { error } = await supabase.auth.signOut()
        if (error) throw error
        location.reload()
    }

    return (
        <SupabaseAuthContext.Provider
            value={{
                isAuthenticated,
                user,
                login,
                logout,
                isLoading,
            }}
        >
            {children}
        </SupabaseAuthContext.Provider>
    )
}

export function useSupabaseAuth() {
    const context = useContext(SupabaseAuthContext)
    if (context === undefined) {
        throw new Error('useSupabaseAuth must be used within SupabaseAuthProvider')
    }
    return context
}