'use client';

import { useState } from 'react';
import {
    BookProject,
    ChatMessage,
    UserProfile,
} from '@/lib/types';
import api from '@/lib/api';

export const useChat = () => {
    const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
    const [isGenerating, setIsGenerating] = useState(false);

    const sendMessage = async (
        project: BookProject,
        context: string,
        text: string,
        user: UserProfile,
        incrementUsage: () => void
    ) => {
        const userMsg: ChatMessage = {
            id: Date.now().toString(),
            role: 'user',
            text: text
        };
        setChatHistory(prev => [...prev, userMsg]);
        setIsGenerating(true);

        try {
            const response = await api.ai.generate(
                project,
                context === 'global' ? '' : context,
                text,
                user
            );

            incrementUsage();

            const aiMsg: ChatMessage = {
                id: (Date.now() + 1).toString(),
                role: 'model',
                text: response.text,
                responseType: response.type
            };
            setChatHistory(prev => [...prev, aiMsg]);
        } catch {
            setChatHistory(prev => [...prev, {
                id: Date.now().toString(),
                role: 'model',
                text: "Désolé, une erreur est survenue lors de la génération."
            }]);
        } finally {
            setIsGenerating(false);
        }
    };

    return { chatHistory, isGenerating, sendMessage };
};
