import { useState } from 'react';
import { useChat } from '../context/ChatProvider';
import type { MindSpaceChatContext, MindSpaceSaveCategory, PortalUser } from '../types';
import { SpaceChatFab } from './SpaceChatFab';
import { SpaceChatPanel } from './SpaceChatPanel';

export function MindSpaceSpaceChat({
  context,
  user,
  onOpenFullChat,
  onPageSaved,
  open: controlledOpen,
  onOpenChange,
  variant = 'default',
  chatBridge,
  hideOpenFullChat = false,
  title,
}: {
  context: MindSpaceChatContext;
  user: PortalUser;
  onOpenFullChat: () => void;
  onPageSaved?: (result: {
    kind: 'page' | 'category';
    pageId?: string;
    categoryCode?: MindSpaceSaveCategory;
  }) => void;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  variant?: 'default' | 'overlay';
  chatBridge?: import('../hooks/usePageEditSubChat').PageEditSubChatBridge;
  hideOpenFullChat?: boolean;
  title?: string;
}) {
  const { chatState, pendingTool } = useChat();
  const [internalOpen, setInternalOpen] = useState(false);
  const open = controlledOpen ?? internalOpen;
  const setOpen = onOpenChange ?? setInternalOpen;
  const wrapperClass =
    variant === 'overlay' ? 'space-chat-stack space-chat-stack-overlay' : 'space-chat-stack';

  return (
    <div className={wrapperClass}>
      <SpaceChatFab
        open={open}
        streaming={chatState === 'streaming'}
        pendingTool={Boolean(pendingTool)}
        onClick={() => setOpen(!open)}
      />
      <SpaceChatPanel
        open={open}
        context={context}
        user={user}
        onClose={() => setOpen(false)}
        onOpenFullChat={onOpenFullChat}
        onPageSaved={onPageSaved}
        chatBridge={chatBridge}
        hideOpenFullChat={hideOpenFullChat}
        title={title}
      />
    </div>
  );
}
