import React, { useEffect } from 'react';
import { PanelPayload, TerminalEntry } from '../../types/terminal';
import { CompanyPanel } from '../Panels/CompanyPanel';
import { PortfolioPanel } from '../Panels/PortfolioPanel';
import { NewsPanel } from '../Panels/NewsPanel';
import { AnalysisPanel } from '../Panels/AnalysisPanel';

interface TerminalOutputProps {
  history: TerminalEntry[];
  outputRef: React.RefObject<HTMLDivElement | null>;
}

export const TerminalOutput: React.FC<TerminalOutputProps> = ({ history, outputRef }) => {
  // Auto-scroll to bottom when history changes
  useEffect(() => {
    if (outputRef.current) {
      outputRef.current.scrollTop = outputRef.current.scrollHeight;
    }
  }, [history, outputRef]);

  const renderContent = (entry: TerminalEntry) => {
    if (typeof entry.content === 'string') {
      const lines = entry.content.split('\n');
      return (
        <div className="whitespace-pre-wrap font-mono text-[14px] leading-relaxed">
          {lines.map((line, i) => (
            <div key={i}>{line || '\u00A0'}</div>
          ))}
        </div>
      );
    }

    return null;
  };

  const getEntryColor = (type: TerminalEntry['type']) => {
    switch (type) {
      case 'command':
        return 'text-[#e0e0e0]';
      case 'response':
        return 'text-[#58a6ff]';
      case 'system':
        return 'text-[#888888] italic';
      case 'error':
        return 'text-[#ff4757]';
      case 'panel':
        return '';
      default:
        return 'text-[#e0e0e0]';
    }
  };

  const renderPanel = (entry: TerminalEntry) => {
    if (entry.type !== 'panel' || typeof entry.content === 'string') {
      return null;
    }

    const panelData = entry.content as PanelPayload;

    switch (panelData.type) {
      case 'company':
        return <CompanyPanel company={panelData.data} />;
      case 'portfolio':
        return <PortfolioPanel portfolio={panelData.data} />;
      case 'news':
        return <NewsPanel news={panelData.data} ticker={panelData.ticker} />;
      case 'analysis':
        return <AnalysisPanel analysis={panelData.data} />;
      default:
        return null;
    }
  };

  return (
    <div
      ref={outputRef}
      className="flex-1 overflow-y-auto px-6 py-4 space-y-4"
      style={{
        scrollbarWidth: 'thin',
        scrollbarColor: '#2a2a2a #111111'
      }}
    >
      {history.map((entry) => (
        <div key={entry.id} className="animate-in fade-in slide-in-from-bottom-2 duration-200">
          {/* Entry Header */}
          {entry.type === 'command' && (
            <div className="flex items-start gap-2 mb-1">
              <span className="text-[#58a6ff] font-mono select-none">{'>'}</span>
              <div className={getEntryColor(entry.type)}>
                {renderContent(entry)}
              </div>
            </div>
          )}

          {entry.type !== 'command' && entry.type !== 'panel' && (
            <div className={getEntryColor(entry.type)}>
              {renderContent(entry)}
            </div>
          )}

          {/* Render Panel */}
          {entry.type === 'panel' && renderPanel(entry)}

          {/* Timestamp */}
          {entry.timestamp && (
            <div className="mt-1 text-[10px] text-[#666666] font-mono">
              {entry.timestamp.toLocaleTimeString('en-US', { hour12: false })}
            </div>
          )}
        </div>
      ))}

      {/* Empty State */}
      {history.length === 0 && (
        <div className="text-[#888888] font-mono text-center py-20">
          <div className="text-4xl mb-4">⚡</div>
          <div>Terminal ready. Type a command to get started.</div>
        </div>
      )}
    </div>
  );
};
