import React, { useEffect, useState, useRef } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2, AlertCircle, Clock, FileText, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { getDeployNodeLogs } from '../service';
import type { DeployNodeLogDTO, LogLevel } from '../types';
import dayjs from 'dayjs';

interface DeployNodeLogDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  processInstanceId: string;
  nodeId: string;
  nodeName?: string;
}

const getLevelClass = (level: LogLevel): string => {
  const levelMap: Record<LogLevel, string> = {
    INFO: 'text-blue-600',
    WARN: 'text-yellow-600',
    ERROR: 'text-red-600',
  };
  return levelMap[level] || 'text-gray-600';
};

const DeployNodeLogDialog: React.FC<DeployNodeLogDialogProps> = ({
  open,
  onOpenChange,
  processInstanceId,
  nodeId,
  nodeName,
}) => {
  const [loading, setLoading] = useState(false);
  const [logData, setLogData] = useState<DeployNodeLogDTO | null>(null);
  const scrollAreaRef = useRef<HTMLDivElement>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  const fetchLogs = async () => {
    if (!processInstanceId || !nodeId) return;

    setLoading(true);
    try {
      const response = await getDeployNodeLogs(processInstanceId, nodeId);
      setLogData(response);

      // 如果日志未过期且有新日志，滚动到底部
      if (response && !response.expired && response.logs.length > 0) {
        setTimeout(() => {
          if (scrollAreaRef.current) {
            scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
          }
        }, 100);
      }

      // 如果日志已过期，停止轮询
      if (response?.expired) {
        if (intervalRef.current) {
          clearInterval(intervalRef.current);
          intervalRef.current = null;
        }
      }
    } catch (error) {
      console.error('获取节点日志失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open && processInstanceId && nodeId) {
      setLogData(null);
      fetchLogs();
      
      // 不再自动轮询，只在打开时加载一次
    } else {
      // 关闭时清除定时器
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    }

    return () => {
      // 组件卸载时清除定时器
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [open, processInstanceId, nodeId]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl h-[80vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5 text-primary" />
            节点日志 - {nodeName || nodeId}
            {logData?.expired && (
              <span className="ml-2 text-sm font-normal text-red-500">(日志已过期或不存在)</span>
            )}
          </DialogTitle>
        </DialogHeader>

        <DialogBody className="flex-1 flex flex-col min-h-0">
          {/* 工具栏 */}
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              {logData && !logData.expired && (
                <span>共 {logData.logs.length} 条日志</span>
              )}
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={fetchLogs}
              disabled={loading}
            >
              <RefreshCw className={cn("h-4 w-4 mr-2", loading && "animate-spin")} />
              刷新
            </Button>
          </div>

          {/* 日志内容区域 */}
          {loading && !logData ? (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <Loader2 className="h-8 w-8 animate-spin text-primary mx-auto mb-2" />
                <span className="text-sm text-muted-foreground">加载日志中...</span>
              </div>
            </div>
          ) : logData?.expired ? (
            <div className="flex flex-col items-center justify-center h-full text-muted-foreground">
              <AlertCircle className="h-12 w-12 mb-4 text-muted-foreground/50" />
              <p className="text-lg font-medium">日志已过期或不存在</p>
              <p className="text-sm mt-2">日志通常保留 7 天，请检查部署时间</p>
            </div>
          ) : (
            <div
              className="flex-1 border rounded-md bg-gray-50 overflow-auto"
              ref={scrollAreaRef}
            >
              <div className="p-2 font-mono text-xs w-max min-w-full">
                {logData?.logs && logData.logs.length > 0 ? (
                  (() => {
                    // 计算行号宽度（只计算一次）
                    const lineNumWidth = Math.max(4, String(logData.logs.length).length + 1);

                    return logData.logs.map((log, index) => {
                      // 格式化时间戳为可读格式：2025-11-07 16:27:41.494
                      const timestamp = dayjs(log.timestamp).format('YYYY-MM-DD HH:mm:ss.SSS');

                      return (
                        <div
                          key={log.sequenceId}
                          className="flex items-start px-2 py-0.5 whitespace-nowrap"
                        >
                          {/* 行号 - 动态宽度，右对齐 */}
                          <span
                            className="text-gray-400 flex-shrink-0 text-right select-none"
                            style={{ width: `${lineNumWidth}ch`, marginRight: '1ch' }}
                          >
                            {index + 1}
                          </span>

                          {/* 时间戳 - 可读格式，23个字符 (2025-11-07 16:27:41.494) */}
                          <span
                            className="text-gray-600 flex-shrink-0"
                            style={{ width: '23ch', marginRight: '2ch' }}
                          >
                            {timestamp}
                          </span>

                          {/* 日志级别 - 5个字符，右对齐 */}
                          <span
                            className={cn('flex-shrink-0 font-semibold text-right', getLevelClass(log.level))}
                            style={{ width: '5ch', marginRight: '2ch' }}
                          >
                            {log.level}
                          </span>

                          {/* 日志消息 - 不换行显示 */}
                          <span className="text-gray-800">
                            {log.message}
                          </span>
                        </div>
                      );
                    });
                  })()
                ) : (
                  <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                    <Clock className="h-12 w-12 mb-4 text-muted-foreground/30" />
                    <p className="text-base font-medium">暂无日志</p>
                    <p className="text-sm mt-2">任务可能尚未开始或未产生日志</p>
                  </div>
                )}
              </div>
            </div>
          )}
        </DialogBody>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            关闭
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default DeployNodeLogDialog;

