import React, { useEffect, useRef, useState } from 'react';
import { ILogData } from '../types';
import { logStreamService } from '../service';

interface LogViewerProps {
  processInstanceId: string;
}

const LogViewer: React.FC<LogViewerProps> = ({ processInstanceId }) => {
  const [logs, setLogs] = useState<ILogData[]>([]);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<string>();
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleLog = (log: ILogData) => {
      setLogs((prevLogs) => [...prevLogs, log]);
      // 自动滚动到底部
      setTimeout(() => {
        if (scrollRef.current) {
          scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
      }, 0);
    };

    const handleError = (error: any) => {
      setError('日志流连接已断开');
      setIsConnected(false);
    };

    setIsConnected(true);
    logStreamService.connect(processInstanceId, handleLog, handleError);

    return () => {
      logStreamService.disconnect();
      setIsConnected(false);
    };
  }, [processInstanceId]);

  return (
    <div className="w-full h-[600px] p-4 border rounded-lg shadow-sm bg-white">
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-lg font-medium">实时日志</h3>
        <div className="flex items-center gap-2">
          <span className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`} />
          <span className="text-sm text-gray-500">
            {isConnected ? '已连接' : '未连接'}
          </span>
        </div>
      </div>
      
      <div 
        ref={scrollRef}
        className="h-[500px] w-full rounded-md border p-4 overflow-auto bg-gray-50"
      >
        <div className="font-mono text-sm">
          {logs.map((log, index) => (
            <div
              key={index}
              className={`mb-1 ${log.type === 'STDERR' ? 'text-red-500' : 'text-gray-800'}`}
            >
              <span className="text-gray-400">[{new Date(log.timestamp).toLocaleTimeString()}] </span>
              {log.data}
            </div>
          ))}
          {error && <div className="text-red-500 mt-2">{error}</div>}
        </div>
      </div>
    </div>
  );
};

export default LogViewer; 