import useSWR from 'swr';
import axios from '@/lib/axios';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';

export const useAuth = ({ middleware, redirectIfAuthenticated }: { middleware?: string, redirectIfAuthenticated?: string } = {}) => {
    const router = useRouter();

    const { data: user, error, mutate, isLoading } = useSWR('/api/user', () =>
        axios
            .get('/api/user')
            .then(res => res.data)
            .catch(error => {
                if (error.response.status !== 409) throw error;
                router.push('/verify-email');
            }),
        {
            shouldRetryOnError: (error) => {
                const status = error?.response?.status;
                if (status === 401 || status === 409) {
                    console.warn('[useAuth] 🛑 Blocking retry for 401/409');
                    return false;
                }
                return true; 
            }
        }
    );

    const csrf = () => axios.get('/sanctum/csrf-cookie');

    const register = async ({ setErrors, ...props }: any) => {
        await csrf();
        setErrors([]);
        axios
            .post('/register', props)
            .then(() => mutate())
            .catch(error => {
                if (error.response.status !== 422) throw error;
                setErrors(error.response.data.errors);
            });
    };

    const login = async ({ setErrors, setStatus, ...props }: any) => {
        await csrf();
        setErrors([]);
        setStatus && setStatus(null);
        return axios
            .post('/login', props)
            .then(response => {
                mutate();
                return response;
            })
            .catch(error => {
                if (error.response.status !== 422) throw error;
                setErrors(error.response.data.errors);
                throw error;
            });
    };

    const logout = async () => {
        if (!error) {
            await axios.post('/logout').then(() => mutate());
        }
        window.location.pathname = '/signin';
    };

    const forgotPassword = async ({ setErrors, setStatus, email }: any) => {
        await csrf();
        setErrors([]);
        setStatus(null);

        return axios
            .post('/forgot-password', { email })
            .then(response => setStatus(response.data.message))
            .catch(error => {
                if (error.response.status !== 422) throw error;
                setErrors(error.response.data.errors);
                throw error;
            });
    };

    const resetPassword = async ({ setErrors, setStatus, ...props }: any) => {
        await csrf();
        setErrors([]);
        setStatus(null);

        return axios
            .post('/reset-password', props)
            .then(response => {
                setStatus(response.data.message);
                router.push('/signin?message=' + encodeURIComponent(response.data.message));
            })
            .catch(error => {
                if (error.response.status !== 422) throw error;
                setErrors(error.response.data.errors);
                throw error;
            });
    };

    useEffect(() => {
        if (middleware === 'guest' && redirectIfAuthenticated && user)
            router.push(user.default_landing_page || redirectIfAuthenticated);
        
        // Handle unverified users in auth protected routes
        if (middleware === 'auth' && user && !user.email_verified_at && window.location.pathname !== '/verify-email') {
            router.push('/verify-email');
        }

        // If on verify-email page but already verified, go to dashboard
        if (window.location.pathname === '/verify-email' && user?.email_verified_at) {
            router.push('/dashboard');
        }

        if (middleware === 'auth' && error) logout();
    }, [user, error, middleware, redirectIfAuthenticated, router]);

    const hasRole = (role: string | string[]) => {
        if (!user) return false;
        if (Array.isArray(role)) return role.includes(user.role);
        return user.role === role;
    };

    return {
        user,
        isLoading,
        error,
        mutate,
        register,
        login,
        logout,
        forgotPassword,
        resetPassword,
        hasRole,
        // Convenience getters
        isAdmin: user?.role === 'admin',
        isOwner: user?.role === 'owner',
        isAdminOrOwner: ['admin', 'owner'].includes(user?.role || ''),
    };
};
