'use client';

import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import { usePermissions } from '@/hooks/usePermissions';
import { PageState } from '@/components/common/feedback/PageState';
import {
  Search,
  Filter,
  RefreshCw,
  AlertCircle,
  ChevronDown,
  ChevronUp,
  Copy,
  ExternalLink,
  X,
} from 'lucide-react';
import {
  queryLogs,
  LogItem,
  LogLevel,
  QueryLogParams,
  getLogLevelColor,
  getHttpMethodColor,
  getStatusCodeColor,
  formatDuration,
} from '@/services/api/logs';

/**
 * 日志查询页面
 * 支持多条件筛选和搜索
 */
export default function LogQueryPage() {
  const { t } = useTranslation();
  const { hasPermission, isAdmin } = usePermissions();
  
  const [isLoading, setIsLoading] = useState(false);
  const [logs, setLogs] = useState<LogItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [error, setError] = useState<string | null>(null);
  const [showFilters, setShowFilters] = useState(false);
  const [expandedRow, setExpandedRow] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  // 筛选条件
  const [filters, setFilters] = useState<QueryLogParams>({
    startTime: new Date(Date.now() - 60 * 60 * 1000).toISOString(), // 默认最近1小时
    endTime: new Date().toISOString(),
  });
  const [keyword, setKeyword] = useState('');
  const [timeRange, setTimeRange] = useState('1h');

  const canAccess = isAdmin || hasPermission('log:read');

  // 时间范围选项
  const timeRangeOptions = [
    { value: '1h', label: t.logs.common.timeRange.last1h },
    { value: '6h', label: t.logs.common.timeRange.last6h },
    { value: '24h', label: t.logs.common.timeRange.last24h },
    { value: '7d', label: t.logs.common.timeRange.last7d },
    { value: 'custom', label: t.logs.common.timeRange.custom },
  ];

  // 日志级别选项
  const levelOptions = [
    { value: '', label: t.logs.query.filters.allLevels },
    { value: LogLevel.ERROR, label: t.logs.level.error },
    { value: LogLevel.WARN, label: t.logs.level.warn },
    { value: LogLevel.INFO, label: t.logs.level.info },
    { value: LogLevel.DEBUG, label: t.logs.level.debug },
  ];

  // 更新时间范围
  const handleTimeRangeChange = (value: string) => {
    setTimeRange(value);
    const now = new Date();
    let startTime: Date;
    
    switch (value) {
      case '1h':
        startTime = new Date(now.getTime() - 60 * 60 * 1000);
        break;
      case '6h':
        startTime = new Date(now.getTime() - 6 * 60 * 60 * 1000);
        break;
      case '24h':
        startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        break;
      case '7d':
        startTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        break;
      default:
        return;
    }
    
    setFilters(prev => ({
      ...prev,
      startTime: startTime.toISOString(),
      endTime: now.toISOString(),
    }));
  };

  // 加载日志
  const loadLogs = useCallback(async () => {
    if (!canAccess) return;
    
    setIsLoading(true);
    setError(null);
    
    try {
      const params: QueryLogParams = {
        ...filters,
        keyword: keyword || undefined,
        page,
        limit,
      };
      
      const response = await queryLogs(params);
      setLogs(response.items || []);
      setTotal(response.total || 0);
    } catch (err: unknown) {
      console.error('Failed to load logs:', err);
      const errorMessage = err instanceof Error ? err.message : '';
      if (errorMessage.includes('TIME_RANGE_TOO_LARGE')) {
        setError(t.logs.error.timeRangeTooLarge);
      } else if (errorMessage.includes('TOO_BROAD')) {
        setError(t.logs.error.queryTooBroad);
      } else {
        setError(t.logs.error.queryFailed);
      }
    } finally {
      setIsLoading(false);
    }
  }, [canAccess, filters, keyword, page, limit, t]);

  useEffect(() => {
    loadLogs();
  }, [loadLogs]);

  // 复制到剪贴板
  const copyToClipboard = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  // 重置筛选
  const resetFilters = () => {
    setFilters({
      startTime: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
      endTime: new Date().toISOString(),
    });
    setKeyword('');
    setTimeRange('1h');
    setPage(1);
  };

  // 无权限提示
  if (!canAccess) {
    return (
      <div className="h-full flex items-center justify-center" style={{ backgroundColor: 'var(--bg-secondary)' }}>
        <PageState
          variant="error"
          title={t.common.permissionDenied}
          description={t.common.permissionDeniedDetail}
          layout="center"
          className="mx-auto w-full max-w-2xl border-0 bg-transparent"
        />
      </div>
    );
  }

  const totalPages = Math.ceil(total / limit);

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: 'var(--bg-secondary)' }}>
      <div className="flex-1 overflow-auto">
        <div className="p-6 space-y-6">

          {/* 搜索和筛选栏 */}
          <div className="bg-white rounded-lg p-4 border" style={{ borderColor: '#e5e6eb' }}>
            <div className="flex flex-wrap gap-3">
              {/* 搜索框 */}
              <div className="flex-1 min-w-[200px]">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: 'var(--text-tertiary)' }} />
                  <input
                    type="text"
                    value={keyword}
                    onChange={(e) => setKeyword(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && loadLogs()}
                    placeholder={t.logs.query.searchPlaceholder}
                    className="w-full pl-10 pr-4 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>
              </div>

              {/* 时间范围 */}
              <select
                value={timeRange}
                onChange={(e) => handleTimeRangeChange(e.target.value)}
                className="px-4 py-2 rounded-lg text-sm outline-none transition-all cursor-pointer"
                style={{ 
                  backgroundColor: 'var(--bg-secondary)',
                  color: 'var(--text-primary)',
                  border: 'none'
                }}
                onFocus={(e) => {
                  e.target.style.backgroundColor = 'var(--bg-tertiary)';
                }}
                onBlur={(e) => {
                  e.target.style.backgroundColor = 'var(--bg-secondary)';
                }}
              >
                {timeRangeOptions.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>

              {/* 日志级别 */}
              <select
                value={filters.level || ''}
                onChange={(e) => setFilters(prev => ({ ...prev, level: e.target.value as LogLevel || undefined }))}
                className="px-4 py-2 rounded-lg text-sm outline-none transition-all cursor-pointer"
                style={{ 
                  backgroundColor: 'var(--bg-secondary)',
                  color: 'var(--text-primary)',
                  border: 'none'
                }}
                onFocus={(e) => {
                  e.target.style.backgroundColor = 'var(--bg-tertiary)';
                }}
                onBlur={(e) => {
                  e.target.style.backgroundColor = 'var(--bg-secondary)';
                }}
              >
                {levelOptions.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>

              {/* 更多筛选 */}
              <button
                onClick={() => setShowFilters(!showFilters)}
                className="flex items-center px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{ 
                  backgroundColor: 'var(--bg-secondary)',
                  color: 'var(--text-primary)',
                  border: 'none'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = 'var(--bg-tertiary)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'var(--bg-secondary)';
                }}
              >
                <Filter className="w-4 h-4 mr-2" />
                {t.logs.common.filter}
                {showFilters ? <ChevronUp className="w-4 h-4 ml-2" /> : <ChevronDown className="w-4 h-4 ml-2" />}
              </button>

              {/* 搜索按钮 */}
              <button
                onClick={loadLogs}
                disabled={isLoading}
                className="flex items-center px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{ 
                  backgroundColor: 'var(--lark-blue)',
                  color: 'var(--bg-primary)',
                  border: 'none',
                  opacity: isLoading ? 0.5 : 1,
                  cursor: isLoading ? 'not-allowed' : 'pointer'
                }}
                onMouseEnter={(e) => {
                  if (!isLoading) {
                    e.currentTarget.style.backgroundColor = '#1e5eff';
                  }
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'var(--lark-blue)';
                }}
              >
                {isLoading ? (
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                ) : (
                  <Search className="w-4 h-4 mr-2" />
                )}
                {t.logs.common.search}
              </button>

              {/* 重置 */}
              <button
                onClick={resetFilters}
                className="flex items-center px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{ 
                  backgroundColor: 'var(--bg-secondary)',
                  color: 'var(--text-primary)',
                  border: 'none'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = 'var(--bg-tertiary)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'var(--bg-secondary)';
                }}
              >
                <X className="w-4 h-4 mr-2" />
                {t.logs.common.reset}
              </button>
            </div>

            {/* 高级筛选 */}
            {showFilters && (
              <div className="mt-4 pt-4 grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4" style={{ borderTop: '1px solid #e5e6eb' }}>
                {/* 服务 */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t.logs.query.filters.service}
                  </label>
                  <input
                    type="text"
                    value={filters.service || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, service: e.target.value || undefined }))}
                    placeholder="IAM, Form..."
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* 区域 */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t.logs.query.filters.region}
                  </label>
                  <select
                    value={filters.region || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, region: e.target.value || undefined }))}
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all cursor-pointer"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                    }}
                  >
                    <option value="">{t.logs.query.filters.allRegions}</option>
                    <option value="CN">{t.logs.region.CN}</option>
                    <option value="US">{t.logs.region.US}</option>
                    <option value="UAE">{t.logs.region.UAE}</option>
                  </select>
                </div>

                {/* 用户名 */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t.logs.query.filters.userName}
                  </label>
                  <input
                    type="text"
                    value={filters.userName || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, userName: e.target.value || undefined }))}
                    placeholder="itadmin"
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* 追踪 ID */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t.logs.query.filters.traceId}
                  </label>
                  <input
                    type="text"
                    value={filters.traceId || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, traceId: e.target.value || undefined }))}
                    placeholder="CN-1733..."
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* URL */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {'URL'}
                  </label>
                  <input
                    type="text"
                    value={filters.url || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, url: e.target.value || undefined }))}
                    placeholder="/api/v1/..."
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* 状态码 */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t.logs.query.filters.statusCode}
                  </label>
                  <input
                    type="number"
                    value={filters.statusCode || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, statusCode: e.target.value ? parseInt(e.target.value) : undefined }))}
                    placeholder="200, 500..."
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* 最小响应时间 */}
                <div>
                  <label className="block text-xs font-medium mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t.logs.query.filters.minDuration} (ms)
                  </label>
                  <input
                    type="number"
                    value={filters.minDuration || ''}
                    onChange={(e) => setFilters(prev => ({ ...prev, minDuration: e.target.value ? parseInt(e.target.value) : undefined }))}
                    placeholder="1000"
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all"
                    style={{ 
                      backgroundColor: 'var(--bg-secondary)',
                      color: 'var(--text-primary)',
                      border: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-tertiary)';
                      e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                    }}
                    onBlur={(e) => {
                      e.target.style.backgroundColor = 'var(--bg-secondary)';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                </div>

                {/* 仅错误 */}
                <div className="flex items-center pt-5">
                  <label className="flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={filters.hasError || false}
                      onChange={(e) => setFilters(prev => ({ ...prev, hasError: e.target.checked || undefined }))}
                      className="w-4 h-4 rounded border-2 transition-all cursor-pointer"
                      style={{ 
                        accentColor: 'var(--lark-blue)',
                        borderColor: '#e5e6eb'
                      }}
                    />
                    <span className="ml-2 text-sm" style={{ color: 'var(--text-primary)' }}>
                      {t.logs.query.filters.hasError}
                    </span>
                  </label>
                </div>
              </div>
            )}
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="rounded-lg p-4 border" style={{ 
              backgroundColor: 'rgba(245, 63, 63, 0.1)', 
              borderColor: 'rgba(245, 63, 63, 0.3)' 
            }}>
              <div className="flex items-center">
                <AlertCircle className="w-5 h-5 mr-2" style={{ color: 'var(--error)' }} />
                <span style={{ color: 'var(--error)' }}>{error}</span>
              </div>
            </div>
          )}

          {/* 日志列表 */}
          <div className="bg-white rounded-lg border overflow-hidden" style={{ borderColor: '#e5e6eb' }}>
            {/* 表头 */}
            <div className="grid grid-cols-12 gap-4 px-4 py-3 border-b text-xs font-medium" style={{ 
              backgroundColor: '#fafafa',
              borderColor: '#e5e6eb',
              color: 'var(--text-tertiary)'
            }}>
              <div className="col-span-2">{t.logs.query.columns.timestamp}</div>
              <div className="col-span-1">{t.logs.query.columns.level}</div>
              <div className="col-span-1">{t.logs.query.columns.method}</div>
              <div className="col-span-3">{t.logs.query.columns.url}</div>
              <div className="col-span-1">{t.logs.query.columns.statusCode}</div>
              <div className="col-span-1">{t.logs.query.columns.duration}</div>
              <div className="col-span-1">{t.logs.query.columns.service}</div>
              <div className="col-span-1">{t.logs.query.columns.user}</div>
              <div className="col-span-1">{t.logs.query.columns.actions}</div>
            </div>

            {/* 加载中 */}
            {isLoading && (
              <div className="flex items-center justify-center py-12">
                <RefreshCw className="w-6 h-6 animate-spin" style={{ color: 'var(--lark-blue)' }} />
              </div>
            )}

            {/* 日志行 */}
            {!isLoading && logs.length > 0 && (
              <div style={{ borderTop: '1px solid #f7f8fa' }}>
                {logs.map((log, index) => {
                  const levelColors = getLogLevelColor(log.level);
                  const methodColors = getHttpMethodColor(log.http?.method || 'GET');
                  const statusColors = getStatusCodeColor(log.http?.status_code || 200);
                  const isExpanded = expandedRow === `${index}`;
                  
                  return (
                    <div key={index} className="border-b transition-colors" style={{ borderColor: '#e5e6eb' }}>
                      <div
                        className="grid grid-cols-12 gap-4 px-4 py-3 text-sm cursor-pointer"
                        style={{ 
                          backgroundColor: isExpanded ? '#fafafa' : 'var(--bg-primary)'
                        }}
                        onClick={() => setExpandedRow(isExpanded ? null : `${index}`)}
                        onMouseEnter={(e) => {
                          if (!isExpanded) {
                            e.currentTarget.style.backgroundColor = '#fafafa';
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (!isExpanded) {
                            e.currentTarget.style.backgroundColor = 'var(--bg-primary)';
                          }
                        }}
                      >
                        <div className="col-span-2" style={{ color: 'var(--text-secondary)' }}>
                          {new Date(log['@timestamp']).toLocaleString()}
                        </div>
                        <div className="col-span-1">
                          <span className={`px-2 py-0.5 rounded text-xs font-medium ${levelColors.bg} ${levelColors.text}`}>
                            {log.level}
                          </span>
                        </div>
                        <div className="col-span-1">
                          <span className={`px-2 py-0.5 rounded text-xs font-medium ${methodColors.bg} ${methodColors.text}`}>
                            {log.http?.method}
                          </span>
                        </div>
                        <div className="col-span-3 truncate" title={log.http?.url} style={{ color: 'var(--text-primary)' }}>
                          {log.http?.url}
                        </div>
                        <div className="col-span-1">
                          <span className={`px-2 py-0.5 rounded text-xs font-medium ${statusColors.bg} ${statusColors.text}`}>
                            {log.http?.status_code}
                          </span>
                        </div>
                        <div className="col-span-1" style={{ color: 'var(--text-secondary)' }}>
                          {formatDuration(log.http?.duration_ms || 0)}
                        </div>
                        <div className="col-span-1 truncate" title={log.service?.name} style={{ color: 'var(--text-secondary)' }}>
                          {log.service?.name}
                        </div>
                        <div className="col-span-1 truncate" title={log.user?.name} style={{ color: 'var(--text-secondary)' }}>
                          {log.user?.name || '-'}
                        </div>
                        <div className="col-span-1 flex items-center gap-2">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              copyToClipboard(log.trace?.id || '', `trace-${index}`);
                            }}
                            title={t.logs.query.actions.copyTraceId}
                            className="p-1 transition-colors"
                            style={{ color: copiedId === `trace-${index}` ? 'var(--success)' : 'var(--text-tertiary)' }}
                            onMouseEnter={(e) => {
                              if (copiedId !== `trace-${index}`) {
                                e.currentTarget.style.color = 'var(--lark-blue)';
                              }
                            }}
                            onMouseLeave={(e) => {
                              if (copiedId !== `trace-${index}`) {
                                e.currentTarget.style.color = 'var(--text-tertiary)';
                              }
                            }}
                          >
                            <Copy className="w-4 h-4" />
                          </button>
                          {log.trace?.id && (
                            <a
                              href={`/logs/trace?id=${log.trace.id}`}
                              onClick={(e) => e.stopPropagation()}
                              title={t.logs.query.actions.viewTrace}
                              className="p-1 transition-colors"
                              style={{ color: 'var(--text-tertiary)' }}
                              onMouseEnter={(e) => {
                                e.currentTarget.style.color = 'var(--lark-blue)';
                              }}
                              onMouseLeave={(e) => {
                                e.currentTarget.style.color = 'var(--text-tertiary)';
                              }}
                            >
                              <ExternalLink className="w-4 h-4" />
                            </a>
                          )}
                        </div>
                      </div>

                      {/* 展开详情 */}
                      {isExpanded && (
                        <div className="px-4 py-3 border-t" style={{ backgroundColor: 'var(--bg-secondary)', borderColor: '#e5e6eb' }}>
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                            <div>
                              <span style={{ color: 'var(--text-tertiary)' }}>Trace ID:</span>
                              <p className="font-mono text-xs mt-1" style={{ color: 'var(--text-primary)' }}>
                                {log.trace?.id || '-'}
                              </p>
                            </div>
                            <div>
                              <span style={{ color: 'var(--text-tertiary)' }}>Request ID:</span>
                              <p className="font-mono text-xs mt-1" style={{ color: 'var(--text-primary)' }}>
                                {log.http?.request_id || '-'}
                              </p>
                            </div>
                            <div>
                              <span style={{ color: 'var(--text-tertiary)' }}>IP:</span>
                              <p className="mt-1" style={{ color: 'var(--text-primary)' }}>{log.client?.ip || '-'}</p>
                            </div>
                            <div>
                              <span style={{ color: 'var(--text-tertiary)' }}>Region:</span>
                              <p className="mt-1" style={{ color: 'var(--text-primary)' }}>{log.service?.region || '-'}</p>
                            </div>
                          </div>
                          {log.message && (
                            <div className="mt-3">
                              <span style={{ color: 'var(--text-tertiary)' }}>Message:</span>
                              <p className="mt-1 font-mono text-xs bg-white p-2 rounded border" style={{ 
                                color: 'var(--text-primary)',
                                borderColor: '#e5e6eb'
                              }}>
                                {log.message}
                              </p>
                            </div>
                          )}
                          {log.error && (
                            <div className="mt-3">
                              <span style={{ color: 'var(--error)' }}>Error:</span>
                              <div className="mt-1 p-2 rounded border" style={{
                                backgroundColor: 'rgba(245, 63, 63, 0.1)',
                                borderColor: 'rgba(245, 63, 63, 0.2)'
                              }}>
                                <p className="font-medium" style={{ color: 'var(--error)' }}>
                                  {log.error.type}: {log.error.message}
                                </p>
                                {log.error.stack && (
                                  <pre className="mt-2 text-xs overflow-x-auto" style={{ color: 'var(--error)' }}>
                                    {log.error.stack}
                                  </pre>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}

            {/* 空状态 */}
            {!isLoading && logs.length === 0 && (
              <div className="py-12 flex items-center justify-center">
                <PageState
                  variant="empty"
                  title={t.logs?.query?.empty || t.common.noData}
                  layout="center"
                  className="border-0 bg-transparent"
                />
              </div>
            )}
          </div>

          {/* 分页 */}
          {total > 0 && (
            <div className="flex items-center justify-between">
              <p className="text-sm" style={{ color: 'var(--text-tertiary)' }}>
                {t.common.totalRecords.replace('{total}', total.toLocaleString())}，{t.common.currentPage.replace('{current}', String(page)).replace('{total}', String(totalPages))}
              </p>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                  disabled={page <= 1}
                  className="px-3 py-1.5 rounded text-sm transition-all"
                  style={{ 
                    backgroundColor: page <= 1 ? 'var(--bg-secondary)' : 'var(--bg-primary)',
                    color: page <= 1 ? '#c9cdd4' : 'var(--text-primary)',
                    border: `1px solid ${page <= 1 ? 'var(--bg-secondary)' : '#e5e6eb'}`,
                    cursor: page <= 1 ? 'not-allowed' : 'pointer'
                  }}
                  onMouseEnter={(e) => {
                    if (page > 1) {
                      e.currentTarget.style.backgroundColor = 'var(--bg-secondary)';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (page > 1) {
                      e.currentTarget.style.backgroundColor = 'var(--bg-primary)';
                    }
                  }}
                >
                  {t.common.prevPage}
                </button>
                <span className="px-3 py-1 text-sm" style={{ color: 'var(--text-secondary)' }}>
                  {page} / {totalPages}
                </span>
                <button
                  onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                  disabled={page >= totalPages}
                  className="px-3 py-1.5 rounded text-sm transition-all"
                  style={{ 
                    backgroundColor: page >= totalPages ? 'var(--bg-secondary)' : 'var(--bg-primary)',
                    color: page >= totalPages ? '#c9cdd4' : 'var(--text-primary)',
                    border: `1px solid ${page >= totalPages ? 'var(--bg-secondary)' : '#e5e6eb'}`,
                    cursor: page >= totalPages ? 'not-allowed' : 'pointer'
                  }}
                  onMouseEnter={(e) => {
                    if (page < totalPages) {
                      e.currentTarget.style.backgroundColor = 'var(--bg-secondary)';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (page < totalPages) {
                      e.currentTarget.style.backgroundColor = 'var(--bg-primary)';
                    }
                  }}
                >
                  {t.common.nextPage}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
