import { create } from "zustand";
import { api } from "../lib/api.ts";

export interface MessageEmbed {
  id?: string;
  url: string;
  title?: string;
  description?: string;
  image_url?: string;
  site_name?: string;
}

export interface Message {
  id: string;
  channel_id: string;
  author_id: string;
  author_username: string;
  author_display_name: string | null;
  content: string;
  reply_to?: string | null;
  embeds?: MessageEmbed[];
  created_at: string;
  edited_at: string | null;
}

export interface SearchResultMessage extends Message {
  channel_name?: string;
}

export interface MessageState {
  messagesByChannel: Record<string, Message[]>;
  searchResultsByChannel: Record<string, SearchResultMessage[]>;
  selectedMessageIds: Record<string, Set<string>>; // ponytail: per-channel bulk selection
  isLoading: boolean;
  error: string | null;
  fetchMessages: (channelId: string, before?: string) => Promise<void>;
  sendMessage: (channelId: string, content: string, replyTo?: string) => Promise<Message>;
  searchMessages: (channelId: string, query: string) => Promise<SearchResultMessage[]>;
  addMessage: (message: Message) => void;
  updateMessage: (message: Message) => void;
  removeMessage: (channelId: string, messageId: string) => void;
  bulkDeleteMessages: (channelId: string, messageIds: string[]) => Promise<{ deleted: number }>;
  toggleSelectedMessage: (channelId: string, messageId: string) => void;
  clearSelectedMessages: (channelId: string) => void;
}

export const useMessageStore = create<MessageState>((set) => ({
  messagesByChannel: {},
  searchResultsByChannel: {},
  selectedMessageIds: {},
  isLoading: false,
  error: null,

  fetchMessages: async (channelId, before) => {
    set({ isLoading: true, error: null });
    try {
      const params = before ? `?before=${encodeURIComponent(before)}` : "";
      const messages = await api.get<Message[]>(
        `/channels/${channelId}/messages${params}`,
      );
      set((state) => ({
        messagesByChannel: {
          ...state.messagesByChannel,
          [channelId]: Array.isArray(messages) ? messages : [],
        },
        isLoading: false,
      }));
    } catch (error) {
      set({
        isLoading: false,
        error:
          error instanceof Error
            ? error.message
            : "Failed to fetch messages",
      });
    }
  },

  searchMessages: async (channelId, query) => {
    const results = await api.get<SearchResultMessage[]>(
      `/channels/${channelId}/messages/search?q=${encodeURIComponent(query)}`,
    );
    set((state) => ({
      searchResultsByChannel: {
        ...state.searchResultsByChannel,
        [channelId]: Array.isArray(results) ? results : [],
      },
    }));
    return Array.isArray(results) ? results : [];
  },

  sendMessage: async (channelId, content, replyTo) => {
    const body: { content: string; reply_to?: string } = { content };
    if (replyTo) body.reply_to = replyTo;
    // ponytail: don't append here — WS MESSAGE_CREATE broadcast is the single source of truth.
    // Appending in both places caused double messages when the WS event arrived before the HTTP response.
    const message = await api.post<Message>(
      `/channels/${channelId}/messages`,
      body,
    );
    return message;
  },

  addMessage: (message) =>
    set((state) => {
      const list = state.messagesByChannel[message.channel_id] || [];
      if (list.some((m) => m.id === message.id)) {
        return state;
      }
      return {
        messagesByChannel: {
          ...state.messagesByChannel,
          [message.channel_id]: [...list, message],
        },
      };
    }),

  updateMessage: (message) =>
    set((state) => {
      const list = state.messagesByChannel[message.channel_id] || [];
      return {
        messagesByChannel: {
          ...state.messagesByChannel,
          [message.channel_id]: list.map((m) =>
            m.id === message.id ? message : m,
          ),
        },
      };
    }),

  removeMessage: (channelId, messageId) =>
    set((state) => {
      const list = state.messagesByChannel[channelId] || [];
      return {
        messagesByChannel: {
          ...state.messagesByChannel,
          [channelId]: list.filter((m) => m.id !== messageId),
        },
      };
    }),

  bulkDeleteMessages: async (channelId, messageIds) => {
    const res = await api.post<{ deleted: number }>(
      `/channels/${channelId}/messages/bulk-delete`,
      { messages: messageIds },
    );
    set((state) => {
      const list = state.messagesByChannel[channelId] || [];
      const ids = new Set(messageIds);
      const selected = { ...state.selectedMessageIds };
      delete selected[channelId];
      return {
        messagesByChannel: {
          ...state.messagesByChannel,
          [channelId]: list.filter((m) => !ids.has(m.id)),
        },
        selectedMessageIds: selected,
      };
    });
    return res;
  },

  toggleSelectedMessage: (channelId, messageId) =>
    set((state) => {
      const current = state.selectedMessageIds[channelId] || new Set<string>();
      const next = new Set(current);
      if (next.has(messageId)) {
        next.delete(messageId);
      } else {
        next.add(messageId);
      }
      return {
        selectedMessageIds: {
          ...state.selectedMessageIds,
          [channelId]: next,
        },
      };
    }),

  clearSelectedMessages: (channelId) =>
    set((state) => {
      const next = { ...state.selectedMessageIds };
      delete next[channelId];
      return { selectedMessageIds: next };
    }),
}));
