import { useCallback } from 'react';
import { useChatStore } from '@/store/chatStore';
import { useWebSocket } from './useWebSocket';
import type { ChatMode, MessageAttachment } from '@/types/chat';

export function useChat() {
  const {
    messages,
    isTyping,
    addMessage,
    setTyping,
    clearMessages,
  } = useChatStore();

  const { sendMessage, isConnected } = useWebSocket();

  const send = useCallback(
    (content: string, mode: ChatMode = 'text', attachments?: MessageAttachment[]) => {
      const userMsgId = `user_${Date.now()}`;

      // 添加用户消息
      addMessage({
        id: userMsgId,
        role: 'user',
        content,
        attachments,
        timestamp: Date.now(),
      });

      // 设置输入中状态
      setTyping(true);

      // 发送WebSocket消息
      sendMessage({
        type: 'message',
        content,
        mode,
        attachments,
        timestamp: Date.now(),
        client_msg_id: userMsgId,
      });
    },
    [addMessage, setTyping, sendMessage]
  );

  const sendVoiceStreamMessage = useCallback(
    (msg: import('@/types/chat').WSClientMessage) => {
      sendMessage(msg);
    },
    [sendMessage]
  );

  return {
    messages,
    isTyping,
    isConnected,
    send,
    sendVoiceStreamMessage,
    clearMessages,
  };
}
