import React, { useEffect, useRef } from 'react';
import { SerialLogEntry, ViewMode } from '../types';
import { formatTime, uInt8ArrayToAscii, uInt8ArrayToHex } from '../utils';

interface TerminalProps {
  title: string;
  logs: SerialLogEntry[];
  viewMode: ViewMode;
  isConnected: boolean;
  onClear: () => void;
  onSave: () => void;
  className?: string;
  headerControls?: React.ReactNode;
}

const Terminal: React.FC<TerminalProps> = ({ 
  title, 
  logs, 
  viewMode, 
  isConnected,
  onClear,
  onSave,
  className,
  headerControls
}) => {
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Auto-scroll to bottom on new logs
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [logs]);

  return (
    <div className={`flex flex-col h-full bg-gray-900 border border-gray-800 rounded-lg shadow-xl overflow-hidden ${className}`}>
      {/* Terminal Header */}
      <div className="flex flex-wrap items-center justify-between px-4 py-2 bg-gray-850 border-b border-gray-800 gap-y-2">
        <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
                <div className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500 animate-pulse' : 'bg-red-500'}`} />
                <h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider whitespace-nowrap">{title}</h2>
            </div>
            
            {/* Custom Header Controls (e.g. Baud Rate, Connect Button) */}
            {headerControls && (
                <div className="flex items-center gap-2 border-l border-gray-700 pl-4">
                    {headerControls}
                </div>
            )}
        </div>

        <div className="flex items-center gap-2 ml-auto">
           {/* Save Button (Icon Only) */}
           <button 
             onClick={onSave}
             className="p-1.5 text-indigo-400 hover:text-white hover:bg-indigo-900/50 rounded transition-colors border border-transparent hover:border-indigo-500/30"
             title="Save Logs to File"
           >
             <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
             </svg>
           </button>

           {/* Clear Button (Icon Only - Trash) */}
           <button 
             onClick={onClear}
             className="p-1.5 text-gray-400 hover:text-red-400 hover:bg-red-900/30 rounded transition-colors border border-transparent hover:border-red-500/30"
             title="Clear Logs"
           >
             <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
               <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
             </svg>
           </button>
        </div>
      </div>

      {/* Log Area */}
      <div className="flex-1 overflow-y-auto font-mono text-sm p-4 space-y-1 relative bg-black/50">
        {logs.length === 0 && (
          <div className="absolute inset-0 flex items-center justify-center text-gray-600 pointer-events-none">
            <p>Waiting for data...</p>
          </div>
        )}
        
        {logs.map((log) => (
          <div key={log.id} className="flex gap-3 hover:bg-white/5 p-0.5 rounded transition-colors group">
            <span className="text-gray-600 text-xs select-none w-20 shrink-0">
              [{formatTime(log.timestamp)}]
            </span>
            <span className={`font-bold text-xs w-6 shrink-0 select-none ${
              log.direction === 'TX' ? 'text-blue-400' : 'text-orange-400'
            }`}>
              {log.direction}
            </span>
            <span className={`break-all ${
              log.direction === 'TX' ? 'text-blue-100' : 'text-orange-100'
            }`}>
              {viewMode === ViewMode.ASCII 
                ? uInt8ArrayToAscii(log.data) 
                : uInt8ArrayToHex(log.data)
              }
            </span>
          </div>
        ))}
        <div ref={bottomRef} />
      </div>
    </div>
  );
};

export default Terminal;