import { createContext, useContext, useState, useCallback, ReactNode } from 'react';
import { Grid } from 'antd';

const { useBreakpoint } = Grid;

export interface ChatWindow {
  videoId: number;
  videoTitle: string;
  thumbnailPath?: string | null;
  isExpanded: boolean;
  unreadCount: number;
}

interface ChatBarContextValue {
  windows: ChatWindow[];
  openChat: (videoId: number, videoTitle: string, thumbnailPath?: string | null) => void;
  closeChat: (videoId: number) => void;
  toggleExpanded: (videoId: number) => void;
  minimizeAll: () => void;
  clearUnread: (videoId: number) => void;
  incrementUnread: (videoId: number) => void;
  maxWindows: number;
}

const ChatBarContext = createContext<ChatBarContextValue | undefined>(undefined);

export function useChatBar() {
  const context = useContext(ChatBarContext);
  if (!context) {
    throw new Error('useChatBar must be used within ChatBarProvider');
  }
  return context;
}

export function ChatBarProvider({ children }: { children: ReactNode }) {
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const maxWindows = isMobile ? 1 : 3;

  const [windows, setWindows] = useState<ChatWindow[]>([]);

  const openChat = useCallback(
    (videoId: number, videoTitle: string, thumbnailPath?: string | null) => {
      setWindows((prev) => {
        // Already open? Just expand it
        const existing = prev.find((w) => w.videoId === videoId);
        if (existing) {
          return prev.map((w) =>
            w.videoId === videoId ? { ...w, isExpanded: true, unreadCount: 0 } : w
          );
        }

        const newWindow: ChatWindow = {
          videoId,
          videoTitle,
          thumbnailPath,
          isExpanded: true,
          unreadCount: 0,
        };

        // If at max, close the oldest minimized window (or oldest)
        if (prev.length >= maxWindows) {
          const minimized = prev.filter((w) => !w.isExpanded);
          if (minimized.length > 0) {
            // Remove oldest minimized
            const toRemove = minimized[0]!;
            return [...prev.filter((w) => w.videoId !== toRemove.videoId), newWindow];
          }
          // Remove first window
          return [...prev.slice(1), newWindow];
        }

        return [...prev, newWindow];
      });
    },
    [maxWindows]
  );

  const closeChat = useCallback((videoId: number) => {
    setWindows((prev) => prev.filter((w) => w.videoId !== videoId));
  }, []);

  const toggleExpanded = useCallback((videoId: number) => {
    setWindows((prev) =>
      prev.map((w) =>
        w.videoId === videoId ? { ...w, isExpanded: !w.isExpanded, unreadCount: 0 } : w
      )
    );
  }, []);

  const minimizeAll = useCallback(() => {
    setWindows((prev) => prev.map((w) => ({ ...w, isExpanded: false })));
  }, []);

  const clearUnread = useCallback((videoId: number) => {
    setWindows((prev) =>
      prev.map((w) => (w.videoId === videoId ? { ...w, unreadCount: 0 } : w))
    );
  }, []);

  const incrementUnread = useCallback((videoId: number) => {
    setWindows((prev) =>
      prev.map((w) =>
        w.videoId === videoId && !w.isExpanded
          ? { ...w, unreadCount: w.unreadCount + 1 }
          : w
      )
    );
  }, []);

  return (
    <ChatBarContext.Provider
      value={{
        windows,
        openChat,
        closeChat,
        toggleExpanded,
        minimizeAll,
        clearUnread,
        incrementUnread,
        maxWindows,
      }}
    >
      {children}
    </ChatBarContext.Provider>
  );
}
