import React from 'react';
import { Copy, Check } from 'lucide-react';
import { ResearchCaptureModalController } from '../Research/ResearchCaptureModalController';
import { PortfolioWorkflowState } from '../../hooks/usePortfolioWorkflow';
import {
  resolveTerminalCaptureWorkspaceId,
  resolveTerminalResearchCaptureIntent,
} from '../../lib/terminalResearchCapture';
import { useResearchWorkspacesQuery } from '../../research/researchQueries';
import { useResearchUiStore } from '../../research/researchUiStore';
import {
  PortfolioAction,
  PortfolioActionDraft,
  PortfolioActionSeed,
  TerminalEntry,
} from '../../types/terminal';
import { TerminalOutput } from './TerminalOutput';
import { CommandInput, CommandInputHandle } from './CommandInput';

interface TerminalProps {
  workspaceId: string;
  history: TerminalEntry[];
  inputDraft: string;
  isProcessing: boolean;
  inputRef: React.RefObject<CommandInputHandle | null>;
  onSubmit: (command: string) => void;
  onInputDraftChange: (value: string) => void;
  onRunCommand: (command: string) => void;
  onStartPortfolioAction: (
    action: PortfolioAction,
    seed?: PortfolioActionSeed,
  ) => void;
  onUpdatePortfolioDraft: (patch: Partial<PortfolioActionDraft>) => void;
  onClearPortfolioAction: () => void;
  resetCommandIndex: () => void;
  portfolioWorkflow: PortfolioWorkflowState;
  scrollTop: number;
  stickToBottom: boolean;
  collapsedThinkingEntryIds: string[];
  onScrollStateChange: (
    workspaceId: string,
    scrollState: { scrollTop: number; stickToBottom: boolean },
  ) => void;
  onToggleThinkingEntry: (workspaceId: string, entryId: string) => void;
}

export const Terminal: React.FC<TerminalProps> = ({
  workspaceId,
  history,
  inputDraft,
  isProcessing,
  inputRef,
  onSubmit,
  onInputDraftChange,
  onRunCommand,
  onStartPortfolioAction,
  onUpdatePortfolioDraft,
  onClearPortfolioAction,
  resetCommandIndex,
  portfolioWorkflow,
  scrollTop,
  stickToBottom,
  collapsedThinkingEntryIds,
  onScrollStateChange,
  onToggleThinkingEntry,
}) => {
  const { data: researchWorkspaces = [] } = useResearchWorkspacesQuery();
  const activeResearchWorkspaceId = useResearchUiStore((state) => state.activeWorkspaceId);
  const openCaptureModal = useResearchUiStore((state) => state.openCaptureModal);

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

  const [copied, setCopied] = React.useState(false);

  const handleCopyAll = React.useCallback(() => {
    if (history.length === 0) return;
    const text = history
      .filter((e) => typeof e.content === 'string')
      .map((e) => {
        switch (e.type) {
          case 'command':
            return `> ${e.content}`;
          case 'thinking':
            return `[Thinking] ${e.content}`;
          case 'error':
            return `[Error] ${e.content}`;
          case 'system':
            return `[System] ${e.content}`;
          default:
            return e.content;
        }
      })
      .join('\n\n');
    navigator.clipboard.writeText(text).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }, [history]);

  const handleTerminalSubmit = React.useCallback(
    (command: string) => {
      const researchIntent = resolveTerminalResearchCaptureIntent(command, history);
      if (researchIntent?.terminalNoteSeed) {
        const ticker = researchIntent.terminalNoteSeed.ticker ?? researchIntent.ticker;
        const workspaceId = resolveTerminalCaptureWorkspaceId({
          ticker,
          workspaces: researchWorkspaces,
          activeWorkspaceId: activeResearchWorkspaceId,
        });

        openCaptureModal({
          seedToken: `${Date.now()}-${command.trim().toLowerCase()}`,
          draft: {
            workspaceId: workspaceId ?? defaultWorkspaceId ?? '',
            rawText: researchIntent.terminalNoteSeed.rawText ?? '',
            ticker: ticker ?? '',
          },
          contextLabel: researchIntent.terminalNoteSeed.contextLabel ?? 'Quick capture',
        });
        return;
      }

      onSubmit(command);
    },
    [
      activeResearchWorkspaceId,
      defaultWorkspaceId,
      history,
      onSubmit,
      openCaptureModal,
      researchWorkspaces,
    ],
  );

  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}
          workspaceId={workspaceId}
          value={inputDraft}
          onValueChange={onInputDraftChange}
          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>

      {history.length > 0 && (
        <div className="flex items-center justify-end border-b border-term-border-subtle px-6 py-1">
          <button
            type="button"
            onClick={handleCopyAll}
            className="inline-flex cursor-pointer items-center gap-1.5 text-[11px] font-mono text-term-text-tertiary transition-colors hover:text-term-text disabled:opacity-40"
            title="Copy all messages to clipboard"
          >
            {copied ? (
              <Check className="h-3.5 w-3.5 text-term-accent" />
            ) : (
              <Copy className="h-3.5 w-3.5" />
            )}
            <span>{copied ? 'Copied' : 'Copy All'}</span>
          </button>
        </div>
      )}

      {/* Terminal Output */}
      <TerminalOutput
        workspaceId={workspaceId}
        history={history}
        scrollTop={scrollTop}
        stickToBottom={stickToBottom}
        collapsedThinkingEntryIds={collapsedThinkingEntryIds}
        onScrollStateChange={onScrollStateChange}
        onToggleThinkingEntry={onToggleThinkingEntry}
        onRunCommand={onRunCommand}
        onStartPortfolioAction={onStartPortfolioAction}
      />

      <ResearchCaptureModalController />
    </div>
  );
};
