'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 {
  Clock,
  RefreshCw,
  AlertCircle,
  ExternalLink,
  TrendingUp,
  Server,
  X,
} from 'lucide-react';
import {
  querySlowRequests,
  SlowRequestItem,
  QuerySlowRequestParams,
  formatDuration,
  getHttpMethodColor,
} from '@/services/api/logs';
import { Pagination } from '../_components/Pagination';

/**
 * 慢请求页面
 * 分析响应时间过长的请求
 */
export default function SlowRequestsPage() {
  const { t } = useTranslation();
  const { hasPermission, isAdmin } = usePermissions();
  
  const [isLoading, setIsLoading] = useState(false);
  const [requests, setRequests] = useState<SlowRequestItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [error, setError] = useState<string | null>(null);
  const [summary, setSummary] = useState<{
    total: number;
    avgDuration: number;
    maxDuration: number;
    p95Duration: number;
    p99Duration: number;
    topPaths: { path: string; count: number; avgDuration: number }[];
    byService: Record<string, number>;
  } | null>(null);

  // 筛选条件
  const [filters, setFilters] = useState<QuerySlowRequestParams>({
    startTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
    endTime: new Date().toISOString(),
    thresholdMs: 2000,
  });
  const [timeRange, setTimeRange] = useState('24h');

  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 },
  ];

  // 阈值选项
  const thresholdOptions = [
    { value: 1000, label: '> 1s' },
    { value: 2000, label: '> 2s' },
    { value: 3000, label: '> 3s' },
    { value: 5000, label: '> 5s' },
    { value: 10000, label: '> 10s' },
  ];

  // 更新时间范围
  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 loadRequests = useCallback(async () => {
    if (!canAccess) return;
    
    setIsLoading(true);
    setError(null);
    
    try {
      const params: QuerySlowRequestParams = {
        ...filters,
        page,
        limit,
      };
      
      const response = await querySlowRequests(params);
      setRequests(response.items || []);
      setTotal(response.total || 0);
      setSummary(response.summary || null);
    } catch (err) {
      console.error('Failed to load slow requests:', err);
      setError(t.logs.error.queryFailed);
    } finally {
      setIsLoading(false);
    }
  }, [canAccess, filters, page, limit, t]);

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

  // 无权限提示
  if (!canAccess) {
    return (
      <div className="p-6 flex items-center justify-center">
        <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 bg-[#f7f8fa]">
      {/* 主内容区域 - 可滚动 */}
      <div className="flex-1 overflow-y-auto p-6">
        <div className="max-w-[1400px] mx-auto space-y-4">
          {/* 摘要统计 */}
          {summary && (
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <p className="text-xs text-[#646a73] mb-1">{t.logs.slowRequests.summary.total}</p>
                <p className="text-2xl font-semibold text-[#ff7d00]">{summary.total.toLocaleString()}</p>
              </div>
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <p className="text-xs text-[#646a73] mb-1">{t.logs.slowRequests.summary.avgDuration}</p>
                <p className="text-2xl font-semibold text-[#1f2329]">{formatDuration(summary.avgDuration)}</p>
              </div>
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <p className="text-xs text-[#646a73] mb-1">{t.logs.slowRequests.summary.maxDuration}</p>
                <p className="text-2xl font-semibold text-[#f54a45]">{formatDuration(summary.maxDuration)}</p>
              </div>
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <p className="text-xs text-[#646a73] mb-1">{t.logs.slowRequests.summary.p95Duration}</p>
                <p className="text-2xl font-semibold text-[#1f2329]">{formatDuration(summary.p95Duration)}</p>
              </div>
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <p className="text-xs text-[#646a73] mb-1">{t.logs.slowRequests.summary.p99Duration}</p>
                <p className="text-2xl font-semibold text-[#1f2329]">{formatDuration(summary.p99Duration)}</p>
              </div>
            </div>
          )}

          {/* 分布图表 */}
          {summary && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {/* 最慢路径 TOP */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <div className="flex items-center gap-2 mb-4">
                  <TrendingUp className="w-4 h-4 text-[#ff7d00]" />
                  <h3 className="text-sm font-medium text-[#1f2329]">
                    {t.logs.slowRequests.topPaths}
                  </h3>
                </div>
                {summary.topPaths && summary.topPaths.length > 0 ? (
                  <div className="space-y-3">
                    {summary.topPaths.slice(0, 5).map((item, index) => (
                      <div key={index} className="flex items-center justify-between p-2 bg-[#fff7e8] rounded-md">
                        <div className="flex-1 min-w-0">
                          <p className="text-sm text-[#1f2329] truncate" title={item.path}>
                            {item.path}
                          </p>
                          <p className="text-xs text-[#646a73] mt-0.5">
                            {item.count} 次 • 平均 {formatDuration(item.avgDuration)}
                          </p>
                        </div>
                        <div className="ml-4 text-right">
                          <span className="text-base font-semibold text-[#ff7d00]">
                            {formatDuration(item.avgDuration)}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="py-8 flex items-center justify-center">
                    <PageState
                      variant="empty"
                      title={t.common.noData}
                      layout="center"
                      className="border-0 bg-transparent"
                    />
                  </div>
                )}
              </div>

              {/* 按服务分布 */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <div className="flex items-center gap-2 mb-4">
                  <Server className="w-4 h-4 text-[#3370ff]" />
                  <h3 className="text-sm font-medium text-[#1f2329]">
                    {t.logs.slowRequests.byService}
                  </h3>
                </div>
                {summary.byService && Object.keys(summary.byService).length > 0 ? (
                  <div className="space-y-3">
                    {Object.entries(summary.byService)
                      .sort(([, a], [, b]) => b - a)
                      .slice(0, 5)
                      .map(([service, count]) => {
                        const total = Object.values(summary.byService).reduce((a, b) => a + b, 0);
                        const percentage = ((count / total) * 100).toFixed(1);
                        return (
                          <div key={service}>
                            <div className="flex justify-between text-sm mb-1.5">
                              <span className="text-[#1f2329]">{service}</span>
                              <span className="text-[#646a73] text-xs">{count} ({percentage}%)</span>
                            </div>
                            <div className="w-full bg-[#f2f3f5] rounded-full h-1.5">
                              <div
                                className="bg-[#3370ff] h-1.5 rounded-full transition-all"
                                style={{ width: `${percentage}%` }}
                              />
                            </div>
                          </div>
                        );
                      })}
                  </div>
                ) : (
                  <div className="py-8 flex items-center justify-center">
                    <PageState
                      variant="empty"
                      title={t.common.noData}
                      layout="center"
                      className="border-0 bg-transparent"
                    />
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 筛选栏 */}
          <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
            <div className="flex flex-wrap gap-3">
              {/* 时间范围 */}
              <select
                value={timeRange}
                onChange={(e) => handleTimeRangeChange(e.target.value)}
                className="h-8 px-3 text-sm bg-[#f2f3f5] border-0 rounded-md text-[#1f2329] focus:bg-white focus:ring-1 focus:ring-[#3370ff] transition-all"
              >
                {timeRangeOptions.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>

              {/* 阈值 */}
              <div className="flex items-center gap-2">
                <span className="text-sm text-[#646a73]">
                  {t.logs.slowRequests.thresholdLabel}:
                </span>
                <select
                  value={filters.thresholdMs || 2000}
                  onChange={(e) => setFilters(prev => ({ ...prev, thresholdMs: parseInt(e.target.value) }))}
                  className="h-8 px-3 text-sm bg-[#f2f3f5] border-0 rounded-md text-[#1f2329] focus:bg-white focus:ring-1 focus:ring-[#3370ff] transition-all"
                >
                  {thresholdOptions.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>

              {/* URL 筛选 */}
              <input
                type="text"
                value={filters.url || ''}
                onChange={(e) => setFilters(prev => ({ ...prev, url: e.target.value || undefined }))}
                placeholder="URL..."
                className="h-8 px-3 text-sm bg-[#f2f3f5] border-0 rounded-md text-[#1f2329] placeholder:text-[#8f959e] focus:bg-white focus:ring-1 focus:ring-[#3370ff] transition-all flex-1 min-w-[160px]"
              />

              {/* 服务筛选 */}
              <input
                type="text"
                value={filters.service || ''}
                onChange={(e) => setFilters(prev => ({ ...prev, service: e.target.value || undefined }))}
                placeholder={t.logs.slowRequests.columns.service}
                className="h-8 px-3 text-sm bg-[#f2f3f5] border-0 rounded-md text-[#1f2329] placeholder:text-[#8f959e] focus:bg-white focus:ring-1 focus:ring-[#3370ff] transition-all min-w-[120px]"
              />

              {/* 搜索按钮 */}
              <button
                onClick={loadRequests}
                disabled={isLoading}
                className="h-8 px-4 bg-[#3370ff] text-white text-sm font-medium rounded-md hover:bg-[#2b5fd9] active:bg-[#2555c7] disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-1.5"
              >
                {isLoading ? (
                  <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                ) : (
                  <Clock className="w-3.5 h-3.5" />
                )}
                <span>{t.logs.common.search}</span>
              </button>
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="bg-[#fff3f2] border border-[#ffccc7] rounded-lg p-3">
              <div className="flex items-center gap-2">
                <AlertCircle className="w-4 h-4 text-[#f54a45] flex-shrink-0" />
                <span className="text-sm text-[#f54a45]">{error}</span>
              </div>
            </div>
          )}

          {/* 慢请求列表 */}
          <div className="bg-white rounded-lg border border-[#e5e6eb] shadow-sm overflow-hidden">
            {/* 表头 */}
            {!isLoading && requests.length > 0 && (
              <div className="grid grid-cols-12 gap-4 px-4 h-10 bg-[#f7f8fa] border-b border-[#e5e6eb] text-xs font-medium text-[#646a73] items-center">
                <div className="col-span-2">{t.logs.slowRequests.columns.timestamp}</div>
                <div className="col-span-1">{t.logs.slowRequests.columns.method}</div>
                <div className="col-span-4">{'URL'}</div>
                <div className="col-span-1">{t.logs.slowRequests.columns.duration}</div>
                <div className="col-span-1">{t.logs.slowRequests.columns.service}</div>
                <div className="col-span-1">{t.logs.slowRequests.columns.region}</div>
                <div className="col-span-1">{t.logs.slowRequests.columns.user}</div>
                <div className="col-span-1"></div>
              </div>
            )}

            {/* 加载中 */}
            {isLoading && (
              <div className="flex items-center justify-center py-12">
                <RefreshCw className="w-6 h-6 text-[#8f959e] animate-spin" />
              </div>
            )}

            {/* 慢请求行 */}
            {!isLoading && requests.length > 0 && (
              <div className="divide-y divide-[#e5e6eb]">
                {requests.map((req, index) => {
                  const methodColors = getHttpMethodColor(req.method);
                  const durationClass = req.duration > 5000 ? 'text-[#f54a45]' : req.duration > 3000 ? 'text-[#ff7d00]' : 'text-[#f7ba1e]';
                  
                  return (
                    <div
                      key={index}
                      className="grid grid-cols-12 gap-4 px-4 py-3 text-sm hover:bg-[#fff7e8] transition-colors"
                    >
                      <div className="col-span-2 text-[#646a73] text-xs">
                        {new Date(req.timestamp).toLocaleString()}
                      </div>
                      <div className="col-span-1">
                        <span className={`px-2 py-0.5 rounded text-xs font-medium ${methodColors.bg} ${methodColors.text}`}>
                          {req.method}
                        </span>
                      </div>
                      <div className="col-span-4 text-[#1f2329] truncate text-xs" title={req.url}>
                        {req.url}
                      </div>
                      <div className="col-span-1">
                        <span className={`font-semibold ${durationClass}`}>
                          {formatDuration(req.duration)}
                        </span>
                      </div>
                      <div className="col-span-1 text-[#646a73] truncate text-xs" title={req.service}>
                        {req.service}
                      </div>
                      <div className="col-span-1 text-[#646a73] text-xs">
                        {req.region}
                      </div>
                      <div className="col-span-1 text-[#646a73] truncate text-xs" title={req.user?.name}>
                        {req.user?.name || '-'}
                      </div>
                      <div className="col-span-1 flex justify-end">
                        {req.traceId && (
                          <a
                            href={`/logs/trace?id=${req.traceId}`}
                            title={t.logs.query.actions.viewTrace}
                            className="p-1 text-[#8f959e] hover:text-[#3370ff] inline-flex transition-colors"
                          >
                            <ExternalLink className="w-3.5 h-3.5" />
                          </a>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}

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

          <Pagination
            page={page}
            totalPages={totalPages}
            total={total}
            summary={
              t.common.totalRecords.replace('{total}', total.toLocaleString()) +
              '，' +
              t.common.currentPage
                .replace('{current}', String(page))
                .replace('{total}', String(totalPages))
            }
            prevLabel={t.common.prevPage}
            nextLabel={t.common.nextPage}
            onPageChange={setPage}
          />

        </div>
      </div>
    </div>
  );
}
