import { useCallback, useEffect } from 'react';
import { useWorkspace } from '../../components/Workspace';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { useChat } from '../../hooks/useChat';
import { EmbeddableChat } from './EmbeddableChat';

type ChatPanelInnerProps = {
  scoped: boolean;
  cwdParam?: { root?: string; path: string };
  promptPrefix?: string;
  chatContext: Record<string, string | undefined>;
  setActiveSession: (id: string | null) => void;
  onTurnComplete?: (hadToolCalls: boolean) => void;
};

const ChatPanelInner = ({
  scoped,
  cwdParam,
  promptPrefix,
  chatContext,
  setActiveSession,
  onTurnComplete,
}: ChatPanelInnerProps) => {
  const chat = useChat(undefined, undefined, {
    replaceUrl: false,
    projectScoped: scoped,
    onTurnComplete,
    ...chatContext,
  });

  useEffect(() => {
    setActiveSession(chat.sessionId);
  }, [chat.sessionId]);

  return (
    <EmbeddableChat
      className="h-full"
      chat={chat}
      cwd={cwdParam}
      replaceUrl={false}
      promptPrefix={promptPrefix}
      {...chatContext}
    />
  );
};

export const ChatPanelWrapper = () => {
  const { dashboardId, cwd, root, promptPrefix } = useWorkspace();
  const scoped = cwd !== '~';

  const chatContext =
    dashboardId === 'email' || dashboardId === 'screens/email'
      ? { context: 'email' as const }
      : dashboardId?.startsWith('proj-layout-')
        ? { context: 'project' as const, contextId: dashboardId.replace('proj-layout-', '') }
        : dashboardId && !dashboardId.startsWith('screens/')
          ? { context: 'dashboard' as const, contextId: dashboardId }
          : {};

  const [, setActiveSession] = usePanelChannel<string | null>('chat:active-session', null);
  const [, setPreviewRefresh] = usePanelChannel<number>('preview:refresh', 0);
  const [, setFilesRefresh] = usePanelChannel<number>('files:refresh-signal', 0);

  const onTurnComplete = useCallback(
    (hadToolCalls: boolean) => {
      if (hadToolCalls) {
        setPreviewRefresh(Date.now());
        setFilesRefresh(Date.now());
      }
    },
    [setPreviewRefresh, setFilesRefresh],
  );

  const cwdParam = scoped ? { root, path: cwd } : undefined;

  return (
    <ChatPanelInner
      scoped={scoped}
      cwdParam={cwdParam}
      promptPrefix={promptPrefix}
      chatContext={chatContext}
      setActiveSession={setActiveSession}
      onTurnComplete={onTurnComplete}
    />
  );
};
