'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthGuard } from '@/hooks/useAuthGuard';
import { useTranslation } from '@/hooks/useTranslation';
import {
  getAuditLogs,
  getStatistics,
  AuditLogItem,
  StatisticsResponse,
  getActionLabel,
  getActionColor,
  getStatusLabel,
  getStatusColor,
  formatModuleName,
} from '@/services/api/audit';
import { ApiClientError } from '@/lib/api-client';
import { formatRelativeTime } from '@/lib/format-relative-time';
import {
  FileText,
  AlertTriangle,
  DollarSign,
  Activity,
  Clock,
  CheckCircle,
  XCircle,
  ArrowRight,
  RefreshCw,
  Shield,
  BarChart3,
  TrendingUp,
} from 'lucide-react';

/**
 * 审计概览页面
 * 展示审计系统的关键指标和最近活动
 * 遵循飞书设计风格
 */
export default function AuditOverviewPage() {
  const router = useRouter();
  const { isReady } = useAuthGuard();
  const { t, locale } = useTranslation();
  
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statistics, setStatistics] = useState<StatisticsResponse | null>(null);
  const [recentLogs, setRecentLogs] = useState<AuditLogItem[]>([]);

  useEffect(() => {
    if (!isReady) return;
    loadData();
  }, [isReady]);

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);

      // 获取最近 7 天的统计数据
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - 7);

      const [statsData, logsData] = await Promise.all([
        getStatistics({
          startDate: startDate.toISOString(),
          endDate: endDate.toISOString(),
        }),
        getAuditLogs({ limit: 10, sortBy: 'when', sortOrder: 'desc' }),
      ]);

      setStatistics(statsData);
      setRecentLogs(logsData.items);
    } catch (err) {
      console.error('Failed to load audit data:', err);
      if (err instanceof ApiClientError) {
        setError(err.message);
      } else {
        setError(t.audit.overview.loadFailed);
      }
    } finally {
      setLoading(false);
    }
  };


  // 加载状态
  if (!isReady || loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <RefreshCw className="w-8 h-8 animate-spin mx-auto mb-4" style={{ color: '#3370ff' }} />
          <p style={{ color: '#8f959e' }}>{t.common.loading}</p>
        </div>
      </div>
    );
  }

  // 错误状态
  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <XCircle className="w-12 h-12 mx-auto mb-4" style={{ color: '#f53f3f' }} />
          <p className="font-medium mb-2" style={{ color: '#1f2329' }}>
            {t.audit.overview.loadFailed}
          </p>
          <p className="mb-4" style={{ color: '#8f959e' }}>{error}</p>
          <button
            onClick={loadData}
            className="px-4 py-2 rounded-lg text-white transition-colors"
            style={{ backgroundColor: '#3370ff' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = '#1e5eff';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = '#3370ff';
            }}
          >
            {t.audit.overview.retry}
          </button>
        </div>
      </div>
    );
  }

  const successRate = statistics?.summary.total 
    ? Math.round((statistics.summary.success / statistics.summary.total) * 100)
    : 100;

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
      {/* 内容区域 */}
      <div className="flex-1 overflow-auto">
        <div className="p-6 space-y-6">
          {/* 核心统计卡片 */}
          <section>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 总操作数 */}
              <button
                onClick={() => router.push('/audit/logs')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                {/* 背景装饰 */}
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(51, 112, 255, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #3370ff 0%, #1e5eff 100%)' }}>
                      <Activity className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight" style={{ color: '#646a73' }}>
                      {t.audit.overview.lastSevenDays}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {statistics?.summary.total?.toLocaleString() || 0}
                    </p>
                    <div className="mt-2 flex items-center justify-end text-xs">
                      <CheckCircle className="w-3 h-3 mr-1" style={{ color: '#00b42a' }} />
                      <span className="font-medium" style={{ color: '#00b42a' }}>{successRate}%</span>
                    </div>
                  </div>
                </div>
              </button>

              {/* 财务操作 */}
              <button
                onClick={() => router.push('/audit/financial')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(0, 180, 42, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #00b42a 0%, #009624 100%)' }}>
                      <DollarSign className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight" style={{ color: '#646a73' }}>
                      {t.audit.nav.financial}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {statistics?.summary.financial?.toLocaleString() || 0}
                    </p>
                    <div className="mt-2 flex items-center justify-end text-xs" style={{ color: '#00b42a' }}>
                      <ArrowRight className="w-3 h-3" />
                    </div>
                  </div>
                </div>
              </button>

              {/* 敏感操作 */}
              <button
                onClick={() => router.push('/audit/sensitive')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(255, 125, 0, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #ff7d00 0%, #e66a00 100%)' }}>
                      <AlertTriangle className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight" style={{ color: '#646a73' }}>
                      {t.audit.nav.sensitive}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {statistics?.summary.sensitive?.toLocaleString() || 0}
                    </p>
                    <div className="mt-2 flex items-center justify-end text-xs" style={{ color: '#ff7d00' }}>
                      <ArrowRight className="w-3 h-3" />
                    </div>
                  </div>
                </div>
              </button>

              {/* 失败操作 */}
              <button
                onClick={() => router.push('/audit/logs?status=FAILED')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(245, 63, 63, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #f53f3f 0%, #d63030 100%)' }}>
                      <XCircle className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight" style={{ color: '#646a73' }}>
                      {t.audit.overview.failedOperations}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {statistics?.summary.failed?.toLocaleString() || 0}
                    </p>
                    <div className="mt-2 flex items-center justify-end text-xs" style={{ color: '#f53f3f' }}>
                      <ArrowRight className="w-3 h-3" />
                    </div>
                  </div>
                </div>
              </button>
            </div>
          </section>

          {/* 数据分析区域 */}
          <section>
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
              {/* 模块分布 */}
              <div className="bg-white rounded-lg p-6" style={{ border: '1px solid #e5e6eb' }}>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                    {t.audit.overview.moduleDistribution}
                  </h3>
                  <BarChart3 className="w-4 h-4" style={{ color: '#8f959e' }} />
                </div>
                <div className="space-y-4">
                  {statistics?.byModule.slice(0, 5).map((item) => {
                    const percentage = statistics.summary.total 
                      ? Math.round((item.count / statistics.summary.total) * 100)
                      : 0;
                    
                    return (
                      <div key={item.module}>
                        <div className="flex items-center justify-between text-sm mb-1.5">
                          <span style={{ color: '#646a73' }}>{formatModuleName(item.module, t)}</span>
                          <span className="font-medium tabular-nums" style={{ color: '#1f2329' }}>{item.count}</span>
                        </div>
                        <div className="w-full rounded-full h-1.5" style={{ backgroundColor: '#f2f3f5' }}>
                          <div
                            className="rounded-full h-1.5 transition-all duration-500"
                            style={{ 
                              width: `${percentage}%`,
                              backgroundColor: '#3370ff'
                            }}
                          />
                        </div>
                      </div>
                    );
                  })}
                  {(!statistics?.byModule || statistics.byModule.length === 0) && (
                    <p className="text-sm text-center py-8" style={{ color: '#8f959e' }}>
                      {t.audit.overview.noData}
                    </p>
                  )}
                </div>
              </div>

              {/* 操作类型分布 */}
              <div className="bg-white rounded-lg p-6" style={{ border: '1px solid #e5e6eb' }}>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                    {t.audit.overview.actionTypes}
                  </h3>
                  <Activity className="w-4 h-4" style={{ color: '#8f959e' }} />
                </div>
                <div className="space-y-3">
                  {statistics?.byAction.slice(0, 6).map((item) => {
                    const color = getActionColor(item.action);
                    
                    return (
                      <div key={item.action} className="flex items-center justify-between">
                        <div className="flex items-center">
                          <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${color.bg} ${color.text}`}>
                            {getActionLabel(item.action, t)}
                          </span>
                        </div>
                        <span className="font-medium tabular-nums" style={{ color: '#1f2329' }}>{item.count}</span>
                      </div>
                    );
                  })}
                  {(!statistics?.byAction || statistics.byAction.length === 0) && (
                    <p className="text-sm text-center py-8" style={{ color: '#8f959e' }}>
                      {t.audit.overview.noData}
                    </p>
                  )}
                </div>
              </div>

              {/* 每日趋势 */}
              <div className="bg-white rounded-lg p-6" style={{ border: '1px solid #e5e6eb' }}>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                    {t.audit.overview.dailyTrend}
                  </h3>
                  <TrendingUp className="w-4 h-4" style={{ color: '#8f959e' }} />
                </div>
                <div className="space-y-3">
                  {statistics?.byDay.slice(-7).map((item) => {
                    const maxCount = Math.max(...(statistics.byDay.map(d => d.count) || [1]));
                    const percentage = (item.count / maxCount) * 100;
                    const date = new Date(item.date);
                    const dayName = date.toLocaleDateString(locale === 'zh' ? 'zh-CN' : 'en-US', { weekday: 'short' });
                    
                    return (
                      <div key={item.date} className="flex items-center">
                        <span className="w-10 text-xs" style={{ color: '#8f959e' }}>{dayName}</span>
                        <div className="flex-1 mx-3">
                          <div className="w-full rounded-full h-1.5" style={{ backgroundColor: '#f2f3f5' }}>
                            <div
                              className="rounded-full h-1.5 transition-all duration-500"
                              style={{ 
                                width: `${percentage}%`,
                                backgroundColor: '#3370ff'
                              }}
                            />
                          </div>
                        </div>
                        <span className="w-10 text-xs font-medium text-right tabular-nums" style={{ color: '#1f2329' }}>
                          {item.count}
                        </span>
                      </div>
                    );
                  })}
                  {(!statistics?.byDay || statistics.byDay.length === 0) && (
                    <p className="text-sm text-center py-8" style={{ color: '#8f959e' }}>
                      {t.audit.overview.noData}
                    </p>
                  )}
                </div>
              </div>
            </div>
          </section>

          {/* 最近活动 */}
          <section>
            <div className="bg-white rounded-lg" style={{ border: '1px solid #e5e6eb' }}>
              <div className="p-5 border-b" style={{ borderColor: '#e5e6eb' }}>
                <div className="flex items-center justify-between">
                  <h3 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                    {t.audit.overview.recentActivity}
                  </h3>
                  <button
                    onClick={() => router.push('/audit/logs')}
                    className="text-sm flex items-center transition-colors"
                    style={{ color: '#3370ff' }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = '#1e5eff';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = '#3370ff';
                    }}
                  >
                    {t.audit.overview.viewAll}
                    <ArrowRight className="w-4 h-4 ml-1" />
                  </button>
                </div>
              </div>
              <div>
                {recentLogs.map((log, index) => {
                  const actionColor = getActionColor(log.action);
                  const statusColor = getStatusColor(log.status);
                  
                  return (
                    <button
                      key={log.id}
                      onClick={() => router.push(`/audit/logs/${log.id}`)}
                      className="w-full p-4 transition-colors text-left"
                      style={{ 
                        borderBottom: index < recentLogs.length - 1 ? '1px solid #e5e6eb' : 'none',
                        backgroundColor: 'transparent'
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = '#f7f8fa';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'transparent';
                      }}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex items-start space-x-3 flex-1">
                          <div className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 ${actionColor.bg}`}>
                            <FileText className={`w-5 h-5 ${actionColor.text}`} />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center space-x-2 mb-1">
                              <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${actionColor.bg} ${actionColor.text}`}>
                                {getActionLabel(log.action, t)}
                              </span>
                              <span className="font-medium truncate" style={{ color: '#1f2329' }}>
                                {formatModuleName(log.module, t)}
                              </span>
                              {log.isSensitive && (
                                <AlertTriangle className="w-3.5 h-3.5 flex-shrink-0" style={{ color: '#ff7d00' }} />
                              )}
                              {log.isFinancial && (
                                <DollarSign className="w-3.5 h-3.5 flex-shrink-0" style={{ color: '#00b42a' }} />
                              )}
                            </div>
                            <p className="text-sm line-clamp-1 mb-2" style={{ color: '#646a73' }}>
                              {log.what}
                            </p>
                            <div className="flex items-center space-x-3 text-xs" style={{ color: '#8f959e' }}>
                              <span className="truncate">{log.user?.displayName || log.user?.username || log.who}</span>
                              <span>•</span>
                              <span>{log.ipAddress}</span>
                            </div>
                          </div>
                        </div>
                        <div className="flex flex-col items-end space-y-2 ml-4 flex-shrink-0">
                          <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${statusColor.bg} ${statusColor.text}`}>
                            {getStatusLabel(log.status, t)}
                          </span>
                          <span className="text-xs flex items-center" style={{ color: '#8f959e' }}>
                            <Clock className="w-3 h-3 mr-1" />
                            {formatRelativeTime(log.when, t.audit.relativeTime)}
                          </span>
                        </div>
                      </div>
                    </button>
                  );
                })}
                {recentLogs.length === 0 && (
                  <div className="p-12 text-center">
                    <FileText className="w-12 h-12 mx-auto mb-4" style={{ color: '#c9cdd4' }} />
                    <p style={{ color: '#8f959e' }}>{t.audit.overview.noLogs}</p>
                  </div>
                )}
              </div>
            </div>
          </section>

          {/* SOX 合规信息 */}
          <section>
            <div className="bg-white rounded-lg p-5 flex items-center justify-between" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex items-center">
                <div className="w-10 h-10 rounded-lg flex items-center justify-center mr-3" style={{ backgroundColor: 'rgba(0, 180, 42, 0.1)' }}>
                  <Shield className="w-5 h-5" style={{ color: '#00b42a' }} />
                </div>
                <div>
                  <p className="text-sm font-medium" style={{ color: '#1f2329' }}>
                    {t.audit.soxCompliance}
                  </p>
                  <p className="text-xs" style={{ color: '#8f959e' }}>
                    {t.audit.overview.soxComplianceDesc}
                  </p>
                </div>
              </div>
              <button
                onClick={() => router.push('/audit/integrity')}
                className="text-sm flex items-center transition-colors"
                style={{ color: '#3370ff' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.color = '#1e5eff';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.color = '#3370ff';
                }}
              >
                {t.audit.overview.verifyIntegrity}
                <ArrowRight className="w-4 h-4 ml-1" />
              </button>
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}
