import React from 'react';
import { ResearchCaptureModal } from '../Research/ResearchCaptureModal';
import { PortfolioWorkflowState } from '../../hooks/usePortfolioWorkflow';
import {
  resolveTerminalCaptureWorkspaceId,
  resolveTerminalResearchCaptureIntent,
} from '../../lib/terminalResearchCapture';
import {
  NoteCaptureResult,
  ResearchWorkspace,
} from '../../types/research';
import type { ResearchComposerState } from '../../hooks/useResearchComposer';
import {
  PortfolioAction,
  PortfolioActionDraft,
  PortfolioActionSeed,
  TerminalEntry,
} from '../../types/terminal';
import { TerminalOutput } from './TerminalOutput';
import { CommandInput, CommandInputHandle } from './CommandInput';

interface TerminalProps {
  history: TerminalEntry[];
  isProcessing: boolean;
  outputRef: React.RefObject<HTMLDivElement | null>;
  inputRef: React.RefObject<CommandInputHandle | null>;
  onSubmit: (command: string) => void;
  onRunCommand: (command: string) => void;
  onStartPortfolioAction: (
    action: PortfolioAction,
    seed?: PortfolioActionSeed,
  ) => void;
  onUpdatePortfolioDraft: (patch: Partial<PortfolioActionDraft>) => void;
  onClearPortfolioAction: () => void;
  resetCommandIndex: () => void;
  portfolioWorkflow: PortfolioWorkflowState;
  researchWorkspaces: ResearchWorkspace[];
  activeResearchWorkspaceId: string | null;
  onCaptureResearchNote: (args: {
    draft: ResearchComposerState;
    fallbackTicker?: string;
    explicitWorkspaceId?: string | null;
    autoCreateFromTicker?: boolean;
  }) => Promise<NoteCaptureResult>;
}

export const Terminal: React.FC<TerminalProps> = ({
  history,
  isProcessing,
  outputRef,
  inputRef,
  onSubmit,
  onRunCommand,
  onStartPortfolioAction,
  onUpdatePortfolioDraft,
  onClearPortfolioAction,
  resetCommandIndex,
  portfolioWorkflow,
  researchWorkspaces,
  activeResearchWorkspaceId,
  onCaptureResearchNote,
}) => {
  const [terminalCapture, setTerminalCapture] = React.useState<{
    key: string;
    rawText?: string;
    ticker?: string;
    contextLabel?: string;
  } | null>(null);

  const defaultWorkspaceId = React.useMemo(
    () =>
      resolveTerminalCaptureWorkspaceId({
        ticker: terminalCapture?.ticker,
        workspaces: researchWorkspaces,
        activeWorkspaceId: activeResearchWorkspaceId,
      }),
    [activeResearchWorkspaceId, researchWorkspaces, terminalCapture?.ticker],
  );

  const closeTerminalCapture = React.useCallback(() => {
    setTerminalCapture(null);
    requestAnimationFrame(() => {
      inputRef.current?.focusWithText('');
    });
  }, [inputRef]);

  const handleTerminalSubmit = React.useCallback(
    (command: string) => {
      const researchIntent = resolveTerminalResearchCaptureIntent(command, history);
      if (researchIntent?.terminalNoteSeed) {
        setTerminalCapture({
          key: `${Date.now()}-${command.trim().toLowerCase()}`,
          rawText: researchIntent.terminalNoteSeed.rawText,
          ticker: researchIntent.terminalNoteSeed.ticker ?? researchIntent.ticker,
          contextLabel: researchIntent.terminalNoteSeed.contextLabel,
        });
        return;
      }

      onSubmit(command);
    },
    [history, onSubmit],
  );

  return (
    <div className="relative flex h-full min-w-0 flex-col overflow-hidden bg-term-bg">
      {/* Command Input */}
      <div className="relative z-30 flex-shrink-0 border-b border-term-border bg-term-bg p-6" style={{ overflow: 'visible' }}>
        <CommandInput
          ref={inputRef}
          onSubmit={handleTerminalSubmit}
          onStartPortfolioAction={onStartPortfolioAction}
          onUpdatePortfolioDraft={onUpdatePortfolioDraft}
          onClearPortfolioAction={onClearPortfolioAction}
          isProcessing={isProcessing}
          resetCommandIndex={resetCommandIndex}
          portfolioMode={portfolioWorkflow.isPortfolioMode}
          activePortfolioAction={portfolioWorkflow.activePortfolioAction}
          portfolioDraft={portfolioWorkflow.draft}
          lastPortfolioCommand={portfolioWorkflow.lastPortfolioCommand}
        />
      </div>

      {/* Terminal Output */}
      <TerminalOutput
        history={history}
        outputRef={outputRef}
        onRunCommand={onRunCommand}
        onStartPortfolioAction={onStartPortfolioAction}
      />

      <ResearchCaptureModal
        isOpen={terminalCapture !== null}
        onClose={closeTerminalCapture}
        workspaces={researchWorkspaces}
        defaultWorkspaceId={defaultWorkspaceId}
        defaultTicker={terminalCapture?.ticker}
        defaultRawText={terminalCapture?.rawText}
        seedKey={terminalCapture?.key}
        contextLabel={terminalCapture?.contextLabel ?? 'Quick capture'}
        onSubmitCapture={(draft) =>
          onCaptureResearchNote({
            draft,
            fallbackTicker: terminalCapture?.ticker,
            autoCreateFromTicker: Boolean(terminalCapture?.ticker),
          })
        }
      />
    </div>
  );
};
