import { useCallback, useEffect, useRef } from 'react';
import { useWorkspace } from '../../components/Workspace';
import { useDashboardState } from 'state/useDashboardState';
import { useGlobal } from 'hooks/useGlobal';
import type { TerminalConnectionState } from './Terminal';
import { TerminalView } from './Terminal';

const EMPTY_TERMINALS: Record<string, string> = {};

type CommandTerminalWrapperProps = {
  panelId: string;
  command: string;
  statePrefix: string;
  onPanelRefresh?: () => void;
};

export const CommandTerminalWrapper = ({ panelId, command, statePrefix, onPanelRefresh }: CommandTerminalWrapperProps) => {
  const { dashboardId, cwd } = useWorkspace();
  const stateKey = dashboardId ? `ws-${statePrefix}-${dashboardId}` : `ws-${statePrefix}-default`;
  const { value: terminals, setValue: setTerminals } = useDashboardState<Record<string, string>>(stateKey, EMPTY_TERMINALS);
  const setTerminalsRef = useRef(setTerminals);
  setTerminalsRef.current = setTerminals;

  const sessionId = terminals[panelId];

  useEffect(() => {
    if (!sessionId) {
      setTerminals((prev) => ({ ...prev, [panelId]: crypto.randomUUID() }));
    }
  }, [panelId, sessionId, setTerminals]);

  useEffect(() => {
    return () => {
      setTerminalsRef.current((prev) => {
        const { [panelId]: _, ...rest } = prev;
        return rest;
      });
    };
  }, [panelId]);

  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}
      onPanelRefresh={onPanelRefresh}
      onConnectionChange={onConnectionChange}
    />
  );
};
