import { useState } from 'react';
import { useNhostClient } from '@nhost/react';

export const useAuth = () => {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const nhost = useNhostClient();

    const handleLogin = async (email: string, password: string) => {
        setIsLoading(true);
        setError('');
        try {
            const { session, error } = await nhost.auth.signIn({
                email,
                password,
            });

            if (error) {
                throw new Error(error.message || 'Failed to login. Please check your credentials.');
            }

            if (session) {
                const accessToken = session.accessToken;
                const refreshToken = session.refreshToken;
                const userId = session.user?.id;

                // Store user data in localStorage
                const userData = {
                    email,
                    accessToken,
                    userId,
                    isLoggedIn: true,
                    lastLogin: new Date().toISOString()
                };

                localStorage.setItem('sp_user', JSON.stringify(userData));
                localStorage.setItem('user_id', userId);
                window.dispatchEvent(new Event('userChanged'));

                // Store tokens in HttpOnly cookies (if still needed)
                try {
                    await fetch('/api/auth/store-tokens', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        credentials: 'include',
                        body: JSON.stringify({
                            access_token: accessToken,
                            refresh_token: refreshToken,
                            expires_in: 3600
                        })
                    });
                } catch (error) {
                    console.error('Error storing token in HttpOnly cookie:', error);
                }

                return { success: true, data: { session } };
            } else {
                throw new Error('Login failed: No session returned');
            }
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred';
            setError(errorMessage);
            return { success: false, error: errorMessage };
        } finally {
            setIsLoading(false);
        }
    };

    const handleSignUp = async (email: string, password: string) => {
        setIsLoading(true);
        setError('');
        try {
            const { session, error } = await nhost.auth.signUp({
                email,
                password,
            });

            if (error) {
                throw new Error(error.message || 'Signup failed. Please check your info.');
            }

            if (session) {
                const accessToken = session.accessToken;
                const refreshToken = session.refreshToken;
                const userId = session.user?.id;

                const userData = {
                    email,
                    accessToken,
                    userId,
                    isLoggedIn: true,
                    lastLogin: new Date().toISOString()
                };

                localStorage.setItem('sp_user', JSON.stringify(userData));
                localStorage.setItem('user_id', userId);
                window.dispatchEvent(new Event('userChanged'));

                // Store tokens in HttpOnly cookies (if still needed)
                try {
                    await fetch('/api/auth/store-tokens', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        credentials: 'include',
                        body: JSON.stringify({
                            access_token: accessToken,
                            refresh_token: refreshToken,
                            expires_in: 3600
                        })
                    });
                } catch (error) {
                    console.error('Error storing token in HttpOnly cookie:', error);
                }

                return { success: true, data: { session } };
            } else {
                // Note: NHost may not return a session immediately if email verification is required
                return { 
                    success: true, 
                    data: { 
                        message: 'Signup successful! Please check your email for verification.' 
                    } 
                };
            }
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred';
            setError(errorMessage);
            return { success: false, error: errorMessage };
        } finally {
            setIsLoading(false);
        }
    };

    const handleForgotPassword = async (email: string) => {
        setIsLoading(true);
        setError('');
        try {
            const { error } = await nhost.auth.resetPassword({ email });

            if (error) {
                throw new Error(error.message || 'Failed to send reset email.');
            }

            return { 
                success: true, 
                message: 'If the email exists, a reset link has been sent.' 
            };
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred';
            setError(errorMessage);
            return { success: false, error: errorMessage };
        } finally {
            setIsLoading(false);
        }
    };

    // Additional NHost auth methods you might find useful
    const handleSignOut = async () => {
        setIsLoading(true);
        setError('');
        try {
            const { error } = await nhost.auth.signOut();

            if (error) {
                throw new Error(error.message || 'Failed to sign out.');
            }

            // Clear local storage
            localStorage.removeItem('sp_user');
            localStorage.removeItem('user_id');
            window.dispatchEvent(new Event('userChanged'));

            return { success: true };
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred';
            setError(errorMessage);
            return { success: false, error: errorMessage };
        } finally {
            setIsLoading(false);
        }
    };

    const handleChangePassword = async (newPassword: string) => {
        setIsLoading(true);
        setError('');
        try {
            const { error } = await nhost.auth.changePassword({ newPassword });

            if (error) {
                throw new Error(error.message || 'Failed to change password.');
            }

            return { success: true, message: 'Password changed successfully.' };
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred';
            setError(errorMessage);
            return { success: false, error: errorMessage };
        } finally {
            setIsLoading(false);
        }
    };

    return {
        isLoading,
        error,
        handleLogin,
        handleSignUp,
        handleForgotPassword,
        handleSignOut,
        handleChangePassword,
        setError
    };
};