import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from "react";
import { loadInbox, InboxMessage, markAsRead } from "../../services/inboxService";

interface InboxContextValue {
  messages: InboxMessage[];
  unreadCount: number;
  loading: boolean;
  refreshInbox: () => Promise<void>;
  markMessagesAsRead: (stageIds: string[]) => void;
}

const InboxContext = createContext<InboxContextValue | null>(null);

interface InboxProviderProps {
  children: ReactNode;
}

export function InboxProvider({ children }: InboxProviderProps) {
  const [messages, setMessages] = useState<InboxMessage[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [loading, setLoading] = useState(false);

  const refreshInbox = useCallback(async () => {
    setLoading(true);
    try {
      const response = await loadInbox();
      setMessages(response.inbox);
      setUnreadCount(response.unreadCount);
    } catch (error) {
      console.error("Failed to refresh inbox:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  // Mark messages as read (optimistic update)
  const markMessagesAsRead = useCallback((stageIds: string[]) => {
    if (stageIds.length === 0) return;

    // Optimistic update: به روزرسانی فوری UI
    setMessages((prevMessages) =>
      prevMessages.map((msg) =>
        stageIds.includes(String(msg.stageID)) ? { ...msg, status: "خوانده شده" } : msg
      )
    );
    setUnreadCount((prev) => Math.max(0, prev - stageIds.length));

    // Fire-and-forget API call
    markAsRead(stageIds);
  }, []);

  // Load inbox on mount
  useEffect(() => {
    refreshInbox();
  }, [refreshInbox]);

  return (
    <InboxContext.Provider value={{ messages, unreadCount, loading, refreshInbox, markMessagesAsRead }}>
      {children}
    </InboxContext.Provider>
  );
}

export function useInbox(): InboxContextValue {
  const context = useContext(InboxContext);
  if (!context) {
    throw new Error("useInbox must be used within InboxProvider");
  }
  return context;
}
