'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthGuard } from '@/hooks/useAuthGuard';
import { useTranslation } from '@/hooks/useTranslation';
import { usePermissions } from '@/hooks/usePermissions';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Activity,
  AlertTriangle,
  AlertCircle,
  Clock,
  TrendingUp,
  Server,
  HardDrive,
  Loader2,
  ArrowRight,
  Database,
  BarChart3,
  Shield,
} from 'lucide-react';
import { toast } from '@/lib/toast';
import { formatDate } from '@/utils/format';
import {
  getLogStats,
  queryErrorLogs,
  querySlowRequests,
  LogStats,
  ErrorLogItem,
  SlowRequestItem,
  formatDuration,
  getLogLevelColor,
  LogLevel,
} from '@/services/api/logs';

/**
 * 日志概览页面
 * 显示日志系统的关键指标和统计信息
 */
export default function LogsOverviewPage() {
  const router = useRouter();
  const { isReady } = useAuthGuard();
  const { t, locale } = useTranslation();
  const { hasPermission, isAdmin } = usePermissions();
  
  // ========== 状态管理 ==========
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<LogStats | null>(null);
  const [recentErrors, setRecentErrors] = useState<ErrorLogItem[]>([]);
  const [recentSlowRequests, setRecentSlowRequests] = useState<SlowRequestItem[]>([]);

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

  // ========== 数据加载 ==========
  useEffect(() => {
    if (!isReady || !canAccess) return;
    loadData();
  }, [isReady, canAccess]);

  const loadData = async () => {
    setIsLoading(true);
    
    try {
      // 计算时间范围（最近 24 小时）
      const endTime = new Date().toISOString();
      const startTime = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
      
      // 并行加载数据
      const [statsData, errorsData, slowRequestsData] = await Promise.all([
        getLogStats({ startTime, endTime }).catch(() => null),
        queryErrorLogs({ startTime, endTime, limit: 5 }).catch(() => ({ items: [] })),
        querySlowRequests({ startTime, endTime, limit: 5 }).catch(() => ({ items: [] })),
      ]);
      
      if (statsData) {
        setStats(statsData);
      }
      setRecentErrors(errorsData.items || []);
      setRecentSlowRequests(slowRequestsData.items || []);
      
      console.log('[Logs] Loaded data:', {
        stats: !!statsData,
        errors: errorsData.items?.length || 0,
        slowRequests: slowRequestsData.items?.length || 0,
      });
    } catch (err) {
      console.error('[Logs] Load data error:', err);
      toast.error(t.common.loadFailed);
    } finally {
      setIsLoading(false);
    }
  };

  // ========== UI 渲染 ==========

  // 无权限提示
  if (!canAccess) {
    return (
      <div className="h-full" style={{ backgroundColor: 'var(--bg-secondary)' }}>
        <div className="p-6">
          <Card className="p-6">
            <div className="flex items-center gap-3 text-yellow-800">
              <AlertCircle className="w-5 h-5 text-yellow-600" />
              <span>{t.logs.overview.noAccessPermission}</span>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  // 加载中
  if (!isReady || isLoading) {
    return (
      <div className="h-full flex items-center justify-center" style={{ backgroundColor: 'var(--bg-secondary)' }}>
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--lark-blue)' }} />
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>{t.common.loading}</p>
        </div>
      </div>
    );
  }

  // 统计卡片数据
  const statCards = [
    {
      title: t.logs.overview.totalRequests,
      value: stats?.summary?.totalRequests?.toLocaleString() || '0',
      icon: Activity,
      iconColor: 'text-blue-600',
      bgColor: 'bg-blue-50',
      iconBg: 'bg-blue-100',
    },
    {
      title: t.logs.overview.errorCount,
      value: stats?.summary?.errorCount?.toLocaleString() || '0',
      icon: AlertTriangle,
      iconColor: 'text-red-600',
      bgColor: 'bg-red-50',
      iconBg: 'bg-red-100',
    },
    {
      title: t.logs.overview.warnCount,
      value: stats?.summary?.warnCount?.toLocaleString() || '0',
      icon: AlertCircle,
      iconColor: 'text-yellow-600',
      bgColor: 'bg-yellow-50',
      iconBg: 'bg-yellow-100',
    },
    {
      title: t.logs.overview.slowRequestCount,
      value: stats?.summary?.slowRequestCount?.toLocaleString() || '0',
      icon: Clock,
      iconColor: 'text-orange-600',
      bgColor: 'bg-orange-50',
      iconBg: 'bg-orange-100',
    },
  ];

  // 性能指标
  const performanceMetrics = [
    {
      title: t.logs.overview.avgDuration,
      value: stats?.summary?.avgDuration ? formatDuration(stats.summary.avgDuration) : '-',
      icon: TrendingUp,
    },
    {
      title: t.logs.overview.p95Duration,
      value: stats?.summary?.p95Duration ? formatDuration(stats.summary.p95Duration) : '-',
      icon: BarChart3,
    },
    {
      title: t.logs.overview.p99Duration,
      value: stats?.summary?.p99Duration ? formatDuration(stats.summary.p99Duration) : '-',
      icon: TrendingUp,
    },
    {
      title: t.logs.overview.errorRate,
      value: stats?.summary?.totalRequests 
        ? `${((stats.summary.errorCount / stats.summary.totalRequests) * 100).toFixed(2)}%`
        : '-',
      icon: AlertTriangle,
    },
  ];

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: 'var(--bg-secondary)' }}>
      {/* 内容区域 */}
      <div className="flex-1 overflow-auto">
        <div className="max-w-7xl mx-auto p-6 space-y-6">
          {/* 统计卡片 - 飞书风格 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {statCards.map((card, index) => {
              const Icon = card.icon;
              return (
                <div
                  key={index}
                  className="bg-white rounded-lg p-6 border transition-all hover:shadow-md"
                  style={{ borderColor: '#e5e6eb' }}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <p className="text-xs font-medium mb-2" style={{ color: 'var(--text-tertiary)' }}>
                        {card.title}
                      </p>
                      <p className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>
                        {card.value}
                      </p>
                    </div>
                    <div
                      className="w-12 h-12 rounded-full flex items-center justify-center"
                      style={{ 
                        backgroundColor: card.iconColor === 'text-blue-600' ? 'rgba(51, 112, 255, 0.1)' :
                                        card.iconColor === 'text-red-600' ? 'rgba(245, 63, 63, 0.1)' :
                                        card.iconColor === 'text-yellow-600' ? 'rgba(255, 125, 0, 0.1)' :
                                        'rgba(255, 125, 0, 0.1)'
                      }}
                    >
                      <Icon className={`w-6 h-6 ${card.iconColor}`} />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* 性能指标 */}
          <div className="bg-white rounded-lg p-6 border" style={{ borderColor: '#e5e6eb' }}>
            <div className="flex items-center mb-6">
              <TrendingUp className="w-5 h-5 mr-2" style={{ color: 'var(--success)' }} />
              <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                {t.logs.overview.performanceMetrics}
              </h3>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {performanceMetrics.map((metric, index) => {
                const Icon = metric.icon;
                return (
                  <div
                    key={index}
                    className="text-center p-4 rounded-lg"
                    style={{ backgroundColor: 'var(--bg-secondary)' }}
                  >
                    <Icon className="w-5 h-5 mx-auto mb-2" style={{ color: 'var(--text-secondary)' }} />
                    <p className="text-xs mb-1" style={{ color: 'var(--text-tertiary)' }}>
                      {metric.title}
                    </p>
                    <p className="text-xl font-bold" style={{ color: 'var(--text-primary)' }}>
                      {metric.value}
                    </p>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 分布图表区域 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 服务分布 */}
            <div className="bg-white rounded-lg p-6 border" style={{ borderColor: '#e5e6eb' }}>
              <div className="flex items-center mb-6">
                <Server className="w-5 h-5 mr-2" style={{ color: 'var(--lark-blue)' }} />
                <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                  {t.logs.overview.serviceDistribution}
                </h3>
              </div>
              {stats?.byService && Object.keys(stats.byService).length > 0 ? (
                <div className="space-y-4">
                  {Object.entries(stats.byService)
                    .sort(([, a], [, b]) => b - a)
                    .slice(0, 5)
                    .map(([service, count]) => {
                      const total = Object.values(stats.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-2">
                            <span className="font-medium" style={{ color: 'var(--text-primary)' }}>
                              {service}
                            </span>
                            <span style={{ color: 'var(--text-tertiary)' }}>
                              {count.toLocaleString()} ({percentage}%)
                            </span>
                          </div>
                          <div className="w-full rounded-full h-2" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                            <div
                              className="h-2 rounded-full transition-all"
                              style={{
                                width: `${percentage}%`,
                                backgroundColor: 'var(--lark-blue)'
                              }}
                            />
                          </div>
                        </div>
                      );
                    })}
                </div>
              ) : (
                <div className="text-center py-12">
                  <Database className="w-12 h-12 mx-auto mb-2" style={{ color: '#c9cdd4' }} />
                  <p className="text-sm" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.noDataAvailable}
                  </p>
                </div>
              )}
            </div>

            {/* 级别分布 */}
            <div className="bg-white rounded-lg p-6 border" style={{ borderColor: '#e5e6eb' }}>
              <div className="flex items-center mb-6">
                <Activity className="w-5 h-5 mr-2" style={{ color: 'var(--success)' }} />
                <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                  {t.logs.overview.levelDistribution}
                </h3>
              </div>
              {stats?.byLevel && Object.keys(stats.byLevel).length > 0 ? (
                <div className="space-y-4">
                  {Object.entries(stats.byLevel)
                    .sort(([, a], [, b]) => b - a)
                    .map(([level, count]) => {
                      const total = Object.values(stats.byLevel).reduce((a, b) => a + b, 0);
                      const percentage = ((count / total) * 100).toFixed(1);
                      const colors = getLogLevelColor(level as LogLevel);
                      return (
                        <div key={level}>
                          <div className="flex justify-between text-sm mb-2">
                            <Badge variant="outline" className={`${colors.bg} ${colors.text} border-0`}>
                              {t.logs?.level?.[level.toLowerCase() as keyof typeof t.logs.level] || level}
                            </Badge>
                            <span style={{ color: 'var(--text-tertiary)' }}>
                              {count.toLocaleString()} ({percentage}%)
                            </span>
                          </div>
                          <div className="w-full rounded-full h-2" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                            <div
                              className="h-2 rounded-full transition-all"
                              style={{
                                width: `${percentage}%`,
                                backgroundColor:
                                  level === 'ERROR' ? 'var(--error)' :
                                  level === 'WARN' ? 'var(--warning)' :
                                  level === 'INFO' ? 'var(--lark-blue)' : '#86909c'
                              }}
                            />
                          </div>
                        </div>
                      );
                    })}
                </div>
              ) : (
                <div className="text-center py-12">
                  <BarChart3 className="w-12 h-12 mx-auto mb-2" style={{ color: '#c9cdd4' }} />
                  <p className="text-sm" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.noDataAvailable}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* 磁盘使用 */}
          {stats?.diskUsage && (
            <div className="bg-white rounded-lg p-6 border" style={{ borderColor: '#e5e6eb' }}>
              <div className="flex items-center mb-6">
                <HardDrive className="w-5 h-5 mr-2" style={{ color: 'var(--lark-purple)' }} />
                <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                  {t.logs.overview.diskUsage}
                </h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <div className="text-center p-4 rounded-lg" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                  <p className="text-xs mb-1" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.total}
                  </p>
                  <p className="text-xl font-bold" style={{ color: 'var(--text-primary)' }}>
                    {stats.diskUsage.total}
                  </p>
                </div>
                <div className="text-center p-4 rounded-lg" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                  <p className="text-xs mb-1" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.used}
                  </p>
                  <p className="text-xl font-bold" style={{ color: 'var(--text-primary)' }}>
                    {stats.diskUsage.used}
                  </p>
                </div>
                <div className="text-center p-4 rounded-lg" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                  <p className="text-xs mb-1" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.usageRate}
                  </p>
                  <p
                    className="text-xl font-bold"
                    style={{
                      color: stats.diskUsage.usedPercent > 90 ? 'var(--error)' :
                             stats.diskUsage.usedPercent > 80 ? 'var(--warning)' : 'var(--success)'
                    }}
                  >
                    {stats.diskUsage.usedPercent}%
                  </p>
                </div>
              </div>
              <div className="w-full rounded-full h-3" style={{ backgroundColor: 'var(--bg-secondary)' }}>
                <div
                  className="h-3 rounded-full transition-all"
                  style={{
                    width: `${stats.diskUsage.usedPercent}%`,
                    backgroundColor: stats.diskUsage.usedPercent > 90 ? 'var(--error)' :
                                    stats.diskUsage.usedPercent > 80 ? 'var(--warning)' : 'var(--success)'
                  }}
                />
              </div>
            </div>
          )}

          {/* 最近错误和慢请求 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 最近错误 */}
            <div className="bg-white rounded-lg p-6 border" style={{ borderColor: '#e5e6eb' }}>
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center">
                  <AlertTriangle className="w-5 h-5 mr-2" style={{ color: 'var(--error)' }} />
                  <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                    {t.logs.overview.recentErrors}
                  </h3>
                </div>
                <button
                  onClick={() => router.push('/logs/errors')}
                  className="px-3 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-1"
                  style={{
                    backgroundColor: 'transparent',
                    color: 'var(--lark-blue)'
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = 'rgba(51, 112, 255, 0.1)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = 'transparent';
                  }}
                >
                  {t.logs.overview.viewMore}
                  <ArrowRight className="w-4 h-4" />
                </button>
              </div>
              {recentErrors.length > 0 ? (
                <div className="space-y-3">
                  {recentErrors.map((error, index) => (
                    <div
                      key={index}
                      className="p-3 rounded-lg border transition-colors cursor-pointer"
                      style={{
                        backgroundColor: 'rgba(245, 63, 63, 0.05)',
                        borderColor: 'rgba(245, 63, 63, 0.2)'
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(245, 63, 63, 0.1)';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(245, 63, 63, 0.05)';
                      }}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate" style={{ color: 'var(--error)' }}>
                            {error.error?.message || error.message}
                          </p>
                          <p className="text-xs mt-1 truncate" style={{ color: 'var(--text-secondary)' }}>
                            {error.http?.url} • {error.service?.name}
                          </p>
                        </div>
                        <span className="text-xs ml-2 whitespace-nowrap" style={{ color: 'var(--text-tertiary)' }}>
                          {formatDate(error['@timestamp'], locale)}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-12">
                  <Shield className="w-12 h-12 mx-auto mb-2" style={{ color: 'var(--success)', opacity: 0.2 }} />
                  <p className="text-sm" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.noErrorLogs}
                  </p>
                </div>
              )}
            </div>

            {/* 最近慢请求 */}
            <div className="bg-white rounded-lg p-6 border" style={{ borderColor: '#e5e6eb' }}>
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center">
                  <Clock className="w-5 h-5 mr-2" style={{ color: 'var(--warning)' }} />
                  <h3 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>
                    {t.logs.overview.recentSlowRequests}
                  </h3>
                </div>
                <button
                  onClick={() => router.push('/logs/slow-requests')}
                  className="px-3 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-1"
                  style={{
                    backgroundColor: 'transparent',
                    color: 'var(--lark-blue)'
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = 'rgba(51, 112, 255, 0.1)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = 'transparent';
                  }}
                >
                  {t.logs.overview.viewMore}
                  <ArrowRight className="w-4 h-4" />
                </button>
              </div>
              {recentSlowRequests.length > 0 ? (
                <div className="space-y-3">
                  {recentSlowRequests.map((req, index) => (
                    <div
                      key={index}
                      className="p-3 rounded-lg border transition-colors cursor-pointer"
                      style={{
                        backgroundColor: 'rgba(255, 125, 0, 0.05)',
                        borderColor: 'rgba(255, 125, 0, 0.2)'
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(255, 125, 0, 0.1)';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(255, 125, 0, 0.05)';
                      }}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate" style={{ color: 'var(--warning)' }}>
                            {req.method} {req.url}
                          </p>
                          <p className="text-xs mt-1 truncate" style={{ color: 'var(--text-secondary)' }}>
                            {req.service} • {req.user?.name || 'Anonymous'}
                          </p>
                        </div>
                        <div className="text-right ml-2">
                          <span className="text-sm font-bold" style={{ color: 'var(--warning)' }}>
                            {formatDuration(req.duration)}
                          </span>
                          <p className="text-xs whitespace-nowrap" style={{ color: 'var(--text-tertiary)' }}>
                            {formatDate(req.timestamp, locale)}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-12">
                  <TrendingUp className="w-12 h-12 mx-auto mb-2" style={{ color: 'var(--success)', opacity: 0.2 }} />
                  <p className="text-sm" style={{ color: 'var(--text-tertiary)' }}>
                    {t.logs.overview.noSlowRequests}
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
