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> = {};

export const HostTerminalWrapper = ({ panelId }: { panelId: string }) => {
  const { dashboardId, cwd } = useWorkspace();
  const stateKey = dashboardId ? `ws-host-terminals-${dashboardId}` : 'ws-host-terminals-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;

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