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';

type CommandTerminalWrapperProps = {
  panelId: string;
  command: string;
  statePrefix: string;
};

export const CommandTerminalWrapper = ({ panelId, command, statePrefix }: CommandTerminalWrapperProps) => {
  const { workspace, cwd } = useWorkspace();
  const sessionId = useTerminalSession(panelId, terminalStateKey(statePrefix, workspace));

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

  if (!sessionId) return null;

  const cwdPath = cwd && cwd !== '~' ? (cwd.startsWith('~') ? cwd : `~/${cwd.replace(/^\//, '')}`) : null;
  const fullCommand = cwdPath ? `cd ${cwdPath} && ${command}` : command;

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