import React from 'react';
import type { ResearchComposerState } from '../../hooks/useResearchComposer';
import { PortfolioWorkflowState } from '../../hooks/usePortfolioWorkflow';
import { extractResearchContext } from '../../lib/researchContext';
import { buildTerminalResearchNoteSeed } from '../../lib/terminalResearchNote';
import {
  NoteCaptureResult,
  ResearchNavigationIntent,
  ResearchWorkspace,
} from '../../types/research';
import {
  PortfolioAction,
  PortfolioActionDraft,
  PortfolioActionSeed,
  TerminalEntry,
} from '../../types/terminal';
import { TerminalOutput } from './TerminalOutput';
import { CommandInput, CommandInputHandle } from './CommandInput';
import { ResearchCaptureBar } from '../Research/ResearchCaptureBar';

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;
  onSelectResearchWorkspace: (workspaceId: string) => void;
  onEnsureResearchWorkspace: (request: {
    ticker?: string;
    workspaceId?: string | null;
  }) => Promise<ResearchWorkspace | null>;
  onCaptureResearchNote: (args: {
    draft: ResearchComposerState;
    fallbackTicker?: string;
    explicitWorkspaceId?: string | null;
    autoCreateFromTicker?: boolean;
  }) => Promise<NoteCaptureResult>;
  onOpenResearchContext: (intent: ResearchNavigationIntent) => void;
  onAppendSystemMessage: (message: string) => void;
}

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

  const focusResearchCapture = React.useCallback(() => {
    requestAnimationFrame(() => {
      const element = document.getElementById('research-capture-input');
      if (element instanceof HTMLElement) {
        element.focus();
      }
    });
  }, []);

  const handleTerminalSubmit = React.useCallback(
    (command: string) => {
      const normalized = command.trim().toLowerCase();
      if (normalized === '/notes add') {
        setTerminalNoteSeed({
          key: `${Date.now()}-note-add`,
          ticker: researchContext?.ticker,
          contextLabel: researchContext?.label ?? 'Quick note from terminal',
          rawText: '',
        });
        focusResearchCapture();
        return;
      }

      if (normalized === '/notes current') {
        const seed = buildTerminalResearchNoteSeed(history);
        setTerminalNoteSeed({
          key: `${Date.now()}-note-current`,
          ticker: seed?.ticker ?? researchContext?.ticker,
          contextLabel: seed?.contextLabel ?? researchContext?.label ?? 'Current terminal context',
          rawText:
            seed?.rawText ??
            'Current terminal context is not available yet.\n\nAnalyst note:',
        });
        focusResearchCapture();
        return;
      }

      onSubmit(command);
    },
    [focusResearchCapture, history, onSubmit, researchContext?.label, researchContext?.ticker],
  );

  const captureContextLabel = terminalNoteSeed?.contextLabel ?? researchContext?.label;
  const captureTicker = terminalNoteSeed?.ticker ?? researchContext?.ticker;
  const showResearchCapture = Boolean(terminalNoteSeed);

  return (
    <div className="relative flex h-full min-w-0 flex-col overflow-hidden bg-[#0a0a0a]">
      {/* Subtle scanline effect */}
      <div className="absolute inset-0 pointer-events-none opacity-[0.03] bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(0,0,0,0.1)_2px,rgba(0,0,0,0.1)_4px)]" />

      {/* Command Input */}
      <div className="flex-shrink-0 p-6 border-b border-[#2a2a2a] bg-[#0a0a0a]">
        <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}
        />
        {showResearchCapture ? (
          <div className="mt-4">
            <ResearchCaptureBar
              workspaces={researchWorkspaces}
              defaultWorkspaceId={activeResearchWorkspaceId}
              defaultTicker={captureTicker}
              defaultRawText={terminalNoteSeed?.rawText}
              seedKey={terminalNoteSeed?.key}
              contextLabel={captureContextLabel}
              onWorkspaceChange={onSelectResearchWorkspace}
              onEnsureWorkspace={onEnsureResearchWorkspace}
              onSubmitCapture={(draft) =>
                onCaptureResearchNote({
                  draft,
                  fallbackTicker: captureTicker,
                  explicitWorkspaceId: activeResearchWorkspaceId,
                  autoCreateFromTicker: true,
                })
              }
              onCaptured={(note) => {
                setTerminalNoteSeed(null);
                onAppendSystemMessage(
                  `Saved research note to ${
                    researchWorkspaces.find((workspace) => workspace.id === note.workspaceId)?.name ??
                    note.workspaceId
                  }.`,
                );
              }}
              onOpenResearch={() =>
                onOpenResearchContext({
                  ticker: captureTicker,
                  preferredView: 'canvas',
                })
              }
            />
          </div>
        ) : null}
      </div>

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