import { useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { WorkspaceView, ChatPanelWrapper } from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { useIsMobile } from 'hooks/useIsMobile';
import { defaultLayout } from './defaultLayout';
import { TabList } from './TabList';
import { TabPreview } from './TabPreview';
import { useSelectedTabId } from './shared';

const PROMPT_PREFIX = `You are a browser assistant. The user has connected Chrome tabs via the Officer Browser Relay. You have a 'browser' tool — use it to list tabs, take screenshots, navigate, evaluate JavaScript, and get page info. When asked about a page, take a screenshot first.`;

// This screen's prompt, so this screen's chat panel. See the note in `EmailScreen`.
const BrowserChatPanel = () => <ChatPanelWrapper panelId="browser-chat" promptPrefix={PROMPT_PREFIX} />;

export const BrowserScreen = () => {
  const isMobile = useIsMobile();
  const navigate = useNavigate();
  // No redirect guard: like /email, the bare /browser is the list with nothing open, and a tab id that
  // no longer resolves gets the preview's "no longer attached" state rather than a rewritten address.
  const selectedId = useSelectedTabId();
  const workspace = useDashboardState<LayoutNode>('screens/browser', defaultLayout);

  const components: PanelComponents = useMemo(
    () => ({
      'browser-tabs': TabList,
      'browser-preview': TabPreview,
      'browser-chat': BrowserChatPanel,
    }),
    [],
  );

  const mobilePanelId = isMobile && selectedId ? 'browser-preview' : undefined;
  const onMobileBack = useCallback(() => navigate('/browser'), [navigate]);

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView
        workspace={workspace}
        locked
        components={components}
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={mobilePanelId ? () => onMobileBack() : undefined}
      />
    </div>
  );
};
