import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { devtools } from 'zustand/middleware';

export interface ChatMessage {
  id: string;
  conversation_id: string;
  sender_id: string; // User ID
  sender_username: string; // For display purposes
  content: string;
  created_at: string;
  // status: 'sent' | 'delivered' | 'read' | 'error';
  // type: 'text' | 'image' | 'audio' | 'video' | 'file';
}

export interface Conversation {
  id: string; // UUID from backend
  name: string; // For rooms
  type: 'public' | 'private' | 'direct';
  participants: string[]; // User IDs
  last_message?: ChatMessage;
  unread_count: number;
}

export interface ChatState {
  userId: string | null; // Current authenticated user ID
  username: string | null;
  currentConversationId: string | null;
  conversations: Conversation[];
  messages: Record<string, ChatMessage[]>; // conversationId -> messages[]
  wsToken: string | null;
  wsUrl: string | null;
  wsStatus: 'disconnected' | 'connecting' | 'connected' | 'error';

  // Actions
  setUserId: (userId: string | null, username: string | null) => void;
  setWsToken: (token: string, wsUrl: string) => void;
  setWsStatus: (
    status: 'disconnected' | 'connecting' | 'connected' | 'error',
  ) => void;
  addConversation: (conversation: Conversation) => void;
  setCurrentConversation: (conversationId: string | null) => void;
  addMessage: (message: ChatMessage) => void;
  loadMessages: (conversationId: string, newMessages: ChatMessage[]) => void;
  // sendMessage: (conversationId: string, content: string) => void; // Handled by useChat hook
  // joinConversation: (conversationId: string) => void; // Handled by useChat hook
}

export const useChatStore = create<ChatState>()(
  devtools(
    immer((set) => ({
      userId: null,
      username: null,
      currentConversationId: null,
      conversations: [],
      messages: {},
      wsToken: null,
      wsUrl: null,
      wsStatus: 'disconnected',

      setUserId: (userId, username) =>
        set((state) => {
          state.userId = userId;
          state.username = username;
        }),
      setWsToken: (token, wsUrl) =>
        set((state) => {
          state.wsToken = token;
          state.wsUrl = wsUrl;
        }),
      setWsStatus: (status) =>
        set((state) => {
          state.wsStatus = status;
        }),
      addConversation: (conversation) =>
        set((state) => {
          if (!state.conversations.some((c) => c.id === conversation.id)) {
            state.conversations.push(conversation);
          }
        }),
      setCurrentConversation: (conversationId) =>
        set((state) => {
          state.currentConversationId = conversationId;
        }),
      addMessage: (message) =>
        set((state) => {
          if (!state.messages[message.conversation_id]) {
            state.messages[message.conversation_id] = [];
          }
          state.messages[message.conversation_id].push(message);
        }),
      loadMessages: (conversationId, newMessages) =>
        set((state) => {
          state.messages[conversationId] = newMessages;
        }),
    })),
  ),
);
