'use client';

import { useState, useEffect, useCallback } from 'react';
import { signIn, signOut, useSession } from 'next-auth/react';
import { UserProfile } from '@/lib/types';
import api from '@/lib/api';

export const useAuth = () => {
    const { data: session, status } = useSession();
    const [user, setUser] = useState<UserProfile | null>(null);
    const loading = status === 'loading';

    // Fetch real profile from DB when session is available
    useEffect(() => {
        if (session?.user?.id) {
            fetch('/api/user/profile', { cache: 'no-store' })
                .then(res => res.json())
                .then(dbUser => {
                    const planId = dbUser.plan || 'free';
                    const planDetails = dbUser.planDetails || {
                        id: 'free',
                        displayName: 'Gratuit',
                        maxAiActions: 100,
                        maxProjects: 3
                    };

                    setUser({
                        id: dbUser.id,
                        email: dbUser.email,
                        name: dbUser.name || 'User',
                        avatar: dbUser.avatar,
                        bio: dbUser.bio,
                        subscription: {
                            plan: planId,
                            planDetails: planDetails,
                            startDate: new Date(dbUser.createdAt).getTime(),
                            status: 'active'
                        },
                        usage: {
                            aiActionsCurrent: dbUser.aiActionsUsed || 0,
                            aiActionsLimit: planDetails.maxAiActions,
                            projectsLimit: planDetails.maxProjects,
                        },
                        preferences: { theme: 'light', dailyWordGoal: dbUser.dailyWordGoal || 500, language: 'fr' },
                        stats: {
                            totalWordsWritten: dbUser.totalWords || 0,
                            writingStreak: dbUser.writingStreak || 0,
                            lastWriteDate: dbUser.lastWriteDate ? new Date(dbUser.lastWriteDate).getTime() : 0,
                        },
                    });
                })
                .catch(err => {
                    console.error('Failed to fetch user profile:', err);
                    // Fallback to session data
                    setUser({
                        id: session.user.id || '',
                        email: session.user.email || '',
                        name: session.user.name || 'User',
                        subscription: { plan: 'free', startDate: Date.now(), status: 'active' },
                        usage: { aiActionsCurrent: 0, aiActionsLimit: 100, projectsLimit: 3 },
                        preferences: { theme: 'light', dailyWordGoal: 500, language: 'fr' },
                        stats: { totalWordsWritten: 0, writingStreak: 0, lastWriteDate: 0 },
                    });
                });
        } else if (status === 'unauthenticated') {
            setUser(null);
        }
    }, [session, status]);

    const login = useCallback(async (email: string, password: string) => {
        const result = await signIn('credentials', {
            email,
            password,
            redirect: false,
        });

        if (result?.error) {
            throw new Error(result.error === 'CredentialsSignin'
                ? 'Email ou mot de passe incorrect'
                : result.error
            );
        }
    }, []);

    const signup = useCallback(async (email: string, password: string, name: string) => {
        await api.auth.register(email, password, name);
        const result = await signIn('credentials', {
            email,
            password,
            redirect: false,
        });
        if (result?.error) {
            throw new Error('Compte créé mais erreur de connexion automatique');
        }
    }, []);

    const logout = useCallback(async () => {
        await signOut({ redirect: false });
        setUser(null);
    }, []);

    const incrementUsage = useCallback((serverCount?: number) => {
        if (user) {
            setUser({
                ...user,
                usage: {
                    ...user.usage,
                    aiActionsCurrent: serverCount !== undefined ? serverCount : user.usage.aiActionsCurrent + 1,
                },
            });
        }
    }, [user]);

    const updateProfile = useCallback(async (updates: Partial<UserProfile>) => {
        if (!user) return;

        try {
            // Unpack everything that can be updated into a flat object for the API
            const apiUpdates: any = {};
            if (updates.name !== undefined) apiUpdates.name = updates.name;
            if (updates.avatar !== undefined) apiUpdates.avatar = updates.avatar;
            if (updates.bio !== undefined) apiUpdates.bio = updates.bio;
            if (updates.preferences?.dailyWordGoal !== undefined) apiUpdates.dailyWordGoal = updates.preferences.dailyWordGoal;

            // Make the API call to update DB
            await api.user.updateProfile(apiUpdates);

            // Update local state
            setUser(prev => prev ? { ...prev, ...updates } : null);
        } catch (err) {
            console.error('Failed to update profile:', err);
            throw err;
        }
    }, [user]);

    return { user, login, signup, logout, incrementUsage, updateProfile, loading };
};
