/**
 * Chat hooks
 * React hooks for chat functionality
 */
import { useState, useCallback } from 'react';
import { chatService } from '../services/chatService';
import { Message } from '../types/chat.types';
import { toast } from 'sonner';

export const useChat = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const sendMessage = useCallback(
    async (
      message: string,
      conversationHistory?: Array<{ role: 'user' | 'assistant'; content: string }>,
      context?: string
    ): Promise<string> => {
      setIsLoading(true);
      setError(null);

      try {
        const response = await chatService.sendMessage(
          message,
          conversationHistory,
          context
        );
        return response.message || 'No response received';
      } catch (err: any) {
        const errorMessage =
          err?.message || 'Failed to get response from assistant';
        setError(errorMessage);
        toast.error(errorMessage);
        throw err;
      } finally {
        setIsLoading(false);
      }
    },
    []
  );

  const verifyContent = useCallback(
    async (fieldName: string, content: string): Promise<string> => {
      setIsLoading(true);
      setError(null);

      try {
        const response = await chatService.verifyContent(fieldName, content);
        return response || 'Verification completed';
      } catch (err: any) {
        const errorMessage = err?.message || 'Failed to verify content';
        setError(errorMessage);
        toast.error(errorMessage);
        throw err;
      } finally {
        setIsLoading(false);
      }
    },
    []
  );

  return {
    sendMessage,
    verifyContent,
    isLoading,
    error,
  };
};
