import { create } from 'zustand';
import type { Message, MessageDisplayType } from '@/types/chat';
import type { IoTDevice, BackgroundThinkingStatus } from '@/types/chat';

interface ChatStore {
  messages: Message[];
  isTyping: boolean;

  // 连续对话模式
  continuousMode: boolean;

  // 后台思考状态
  backgroundThinkingStatus: BackgroundThinkingStatus;

  // IoT 设备状态
  iotDevices: IoTDevice[];
  iotDevicesLastUpdated: number | null;

  // 历史消息分页
  hasMoreMessages: boolean;
  isLoadingHistory: boolean;
  historyPage: number;

  // 流式语音识别状态
  voiceInterimText: string;
  voiceFinalText: string;

  // 多气泡消息队列：确保气泡依次出现 + 逐字动画
  messageQueue: Message[];

  addMessage: (message: Message) => void;
  appendToLastMessage: (content: string) => void;
  finishStreaming: () => void;
  /** 将一个消息加入队列，等待上一个气泡的逐字动画完成后再展示 */
  enqueueMessage: (message: Message) => void;
  /** 当前气泡逐字动画完成后调用：关闭 isStreaming，出队下一个 */
  onTypewriterDone: (messageId: string) => void;
  updateMessage: (id: string, updates: Partial<Message>) => void;
  setMessages: (messages: Message[]) => void;
  setTyping: (typing: boolean) => void;
  clearMessages: () => void;

  setContinuousMode: (enabled: boolean) => void;
  setVoiceInterimText: (text: string) => void;
  setVoiceFinalText: (text: string) => void;
  setBackgroundThinkingStatus: (status: BackgroundThinkingStatus) => void;
  setIoTDevices: (devices: IoTDevice[]) => void;

  // 历史消息分页
  setHasMoreMessages: (hasMore: boolean) => void;
  setIsLoadingHistory: (loading: boolean) => void;
  setHistoryPage: (page: number) => void;
  prependMessages: (messages: Message[]) => void;
}

export const useChatStore = create<ChatStore>((set) => ({
  messages: [],
  isTyping: false,
  continuousMode: true,
  backgroundThinkingStatus: 'idle',
  iotDevices: [],
  iotDevicesLastUpdated: null,
  voiceInterimText: '',
  voiceFinalText: '',
  hasMoreMessages: false,
  isLoadingHistory: false,
  historyPage: 1,
  messageQueue: [],

  addMessage: (message) =>
    set((state) => ({
      messages: [
        ...state.messages,
        {
          ...message,
          isStreaming: message.role === 'assistant' ? (message.isStreaming ?? true) : message.isStreaming,
        },
      ],
    })),

  appendToLastMessage: (content) =>
    set((state) => {
      const msgs = [...state.messages];
      const last = msgs[msgs.length - 1];
      if (last && last.role === 'assistant' && last.isStreaming) {
        msgs[msgs.length - 1] = {
          ...last,
          content: last.content + content,
        };
      }
      return { messages: msgs };
    }),

  finishStreaming: () =>
    set((state) => {
      const msgs = [...state.messages];
      const last = msgs[msgs.length - 1];
      if (last && last.role === 'assistant' && last.isStreaming) {
        msgs[msgs.length - 1] = {
          ...last,
          isStreaming: false,
        };
      }
      // Process queued messages after streaming finishes
      const queue = [...state.messageQueue];
      if (queue.length > 0) {
        const next = queue.shift()!;
        return {
          messages: [...msgs, { ...next, isStreaming: true }],
          messageQueue: queue,
          isTyping: false,
        };
      }
      return { messages: msgs, isTyping: false, messageQueue: queue };
    }),

  enqueueMessage: (message) =>
    set((state) => ({
      messageQueue: [...state.messageQueue, message],
    })),

  onTypewriterDone: (messageId) =>
    set((state) => {
      // Mark this specific message as no longer streaming
      const msgs = state.messages.map((m) =>
        m.id === messageId ? { ...m, isStreaming: false } : m
      );
      // Process next queued message
      const queue = [...state.messageQueue];
      if (queue.length > 0) {
        const next = queue.shift()!;
        return {
          messages: [...msgs, { ...next, isStreaming: true }],
          messageQueue: queue,
          isTyping: false,
        };
      }
      return { messages: msgs, isTyping: false, messageQueue: queue };
    }),

  updateMessage: (id, updates) =>
    set((state) => ({
      messages: state.messages.map((m) => (m.id === id ? { ...m, ...updates } : m)),
    })),

  setMessages: (messages) => set({ messages, isTyping: false }),

  setTyping: (typing) => set({ isTyping: typing }),

  clearMessages: () => set({ messages: [], isTyping: false, hasMoreMessages: false, historyPage: 1, messageQueue: [] }),

  setContinuousMode: (enabled) => set({ continuousMode: enabled }),

  setVoiceInterimText: (text) => set({ voiceInterimText: text }),
  setVoiceFinalText: (text) => set({ voiceFinalText: text, voiceInterimText: '' }),

  setBackgroundThinkingStatus: (status) => set({ backgroundThinkingStatus: status }),

  setIoTDevices: (devices) =>
    set({ iotDevices: devices, iotDevicesLastUpdated: Date.now() }),

  setHasMoreMessages: (hasMore) => set({ hasMoreMessages: hasMore }),
  setIsLoadingHistory: (loading) => set({ isLoadingHistory: loading }),
  setHistoryPage: (page) => set({ historyPage: page }),

  prependMessages: (olderMessages) =>
    set((state) => ({
      messages: [...olderMessages, ...state.messages],
    })),
}));

// 辅助函数：根据 role 和 msgType 创建 Message 对象
export function createMessage(
  id: string,
  role: 'user' | 'assistant' | 'system' | 'action',
  content: string,
  timestamp: number,
  opts?: { isStreaming?: boolean; msgType?: MessageDisplayType }
): Message {
  return {
    id,
    role: role === 'action' ? 'action' : role,
    content,
    timestamp,
    isStreaming: opts?.isStreaming ?? false,
    msgType: opts?.msgType ?? (role === 'action' ? 'action' : 'chat'),
  };
}
