import { create } from "zustand";

export interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  audioUrl?: string | null;
  createdAt: string;
}

export interface Conversation {
  id: string;
  title: string;
  messages?: Message[];
  createdAt: string;
  updatedAt: string;
}

interface EchoState {
  // Conversations
  conversations: Conversation[];
  activeConversationId: string | null;
  isLoadingConversations: boolean;

  // Messages
  messages: Message[];
  isLoadingMessages: boolean;

  // Chat state
  isGenerating: boolean;
  streamingContent: string;
  error: string | null;

  // Voice state
  isRecording: boolean;
  isSpeaking: boolean;

  // Settings
  settingsOpen: boolean;
  sidebarOpen: boolean;
  voiceEnabled: boolean;
  autoSpeak: boolean;

  // Actions — Conversations
  setConversations: (conversations: Conversation[]) => void;
  setActiveConversation: (id: string | null) => void;
  loadConversations: () => Promise<void>;
  createConversation: () => Promise<Conversation | null>;
  deleteConversation: (id: string) => Promise<void>;

  // Actions — Messages
  setMessages: (messages: Message[]) => void;
  loadMessages: (conversationId: string) => Promise<void>;
  addMessage: (message: Message) => void;
  updateLastAssistantMessage: (content: string) => void;

  // Actions — Chat
  setIsGenerating: (val: boolean) => void;
  setStreamingContent: (val: string) => void;
  appendStreamingContent: (val: string) => void;
  clearStreamingContent: () => void;
  setError: (err: string | null) => void;

  // Actions — Voice
  setIsRecording: (val: boolean) => void;
  setIsSpeaking: (val: boolean) => void;

  // Actions — Settings
  setSettingsOpen: (val: boolean) => void;
  setSidebarOpen: (val: boolean) => void;
  setVoiceEnabled: (val: boolean) => void;
  setAutoSpeak: (val: boolean) => void;
}

export const useEchoStore = create<EchoState>((set, get) => ({
  // Initial state
  conversations: [],
  activeConversationId: null,
  isLoadingConversations: false,
  messages: [],
  isLoadingMessages: false,
  isGenerating: false,
  streamingContent: "",
  error: null,
  isRecording: false,
  isSpeaking: false,
  settingsOpen: false,
  sidebarOpen: true,
  voiceEnabled: true,
  autoSpeak: true,

  // Conversation actions
  setConversations: (conversations) => set({ conversations }),

  setActiveConversation: (id) => {
    set({ activeConversationId: id, messages: [], streamingContent: "" });
    if (id) {
      get().loadMessages(id);
    }
  },

  loadConversations: async () => {
    set({ isLoadingConversations: true });
    try {
      const res = await fetch("/api/conversations");
      const data = await res.json();
      set({ conversations: data, isLoadingConversations: false });
    } catch {
      set({ isLoadingConversations: false });
    }
  },

  createConversation: async () => {
    try {
      const res = await fetch("/api/conversations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({}),
      });
      const conversation = await res.json();
      set((state) => ({
        conversations: [conversation, ...state.conversations],
        activeConversationId: conversation.id,
        messages: [],
      }));
      return conversation;
    } catch {
      return null;
    }
  },

  deleteConversation: async (id) => {
    try {
      await fetch(`/api/conversations?id=${id}`, { method: "DELETE" });
      const state = get();
      set({
        conversations: state.conversations.filter((c) => c.id !== id),
        activeConversationId:
          state.activeConversationId === id ? null : state.activeConversationId,
        messages: state.activeConversationId === id ? [] : state.messages,
      });
    } catch {
      // silent fail
    }
  },

  // Message actions
  setMessages: (messages) => set({ messages }),

  loadMessages: async (conversationId) => {
    set({ isLoadingMessages: true });
    try {
      const res = await fetch(`/api/conversations/${conversationId}/messages`);
      const data = await res.json();
      set({ messages: data, isLoadingMessages: false });
    } catch {
      set({ isLoadingMessages: false });
    }
  },

  addMessage: (message) =>
    set((state) => ({ messages: [...state.messages, message] })),

  updateLastAssistantMessage: (content) =>
    set((state) => {
      const msgs = [...state.messages];
      for (let i = msgs.length - 1; i >= 0; i--) {
        if (msgs[i].role === "assistant") {
          msgs[i] = { ...msgs[i], content };
          break;
        }
      }
      return { messages: msgs };
    }),

  // Chat actions
  setIsGenerating: (val) => set({ isGenerating: val }),
  setStreamingContent: (val) => set({ streamingContent: val }),
  appendStreamingContent: (val) =>
    set((state) => ({ streamingContent: state.streamingContent + val })),
  clearStreamingContent: () => set({ streamingContent: "" }),
  setError: (err) => set({ error: err }),

  // Voice actions
  setIsRecording: (val) => set({ isRecording: val }),
  setIsSpeaking: (val) => set({ isSpeaking: val }),

  // Settings actions
  setSettingsOpen: (val) => set({ settingsOpen: val }),
  setSidebarOpen: (val) => set({ sidebarOpen: val }),
  setVoiceEnabled: (val) => set({ voiceEnabled: val }),
  setAutoSpeak: (val) => set({ autoSpeak: val }),
}));
