import { useCallback } from 'react';
import { useWorkspace } from '../../components/Workspace';
import { useGlobal } from 'hooks/useGlobal';
import type { TerminalConnectionState } from './Terminal';
import { TerminalView } from './Terminal';
import { terminalStateKey } from './state-key';
import { useTerminalSession } from './use-terminal-session';

export const TerminalWrapper = ({ panelId }: { panelId: string }) => {
  const { workspace, cwd } = useWorkspace();
  const sessionId = useTerminalSession(panelId, terminalStateKey('terminals', workspace));

  const [, setConnState] = useGlobal<TerminalConnectionState>(`terminal-conn-${panelId}`, 'disconnected');
  const onConnectionChange = useCallback((state: TerminalConnectionState) => setConnState(state), [setConnState]);

  if (!sessionId) return null;

  return (
    <TerminalView
      className="h-full w-full p-2"
      sessionId={sessionId}
      cwd={cwd}
      onConnectionChange={onConnectionChange}
    />
  );
};
