'use client';

import { useEffect, useState } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import { PageState } from '@/components/common/feedback/PageState';
import {
  getStatistics,
  StatisticsResponse,
  getActionLabel,
  getActionColor,
  formatModuleName,
} from '@/services/api/audit';
import { ApiClientError } from '@/lib/api-client';
import {
  BarChart3,
  PieChart,
  TrendingUp,
  Calendar,
  RefreshCw,
  XCircle,
  CheckCircle,
  AlertCircle,
} from 'lucide-react';

/**
 * 统计分析页面
 */
export default function AuditStatisticsPage() {
  const { t } = useTranslation();

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statistics, setStatistics] = useState<StatisticsResponse | null>(null);

  // 时间范围
  const [dateRange, setDateRange] = useState(() => {
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 30);
    return {
      startDate: start.toISOString().split('T')[0],
      endDate: end.toISOString().split('T')[0],
    };
  });

  useEffect(() => {
    loadData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateRange]);

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

      const data = await getStatistics({
        startDate: `${dateRange.startDate}T00:00:00.000Z`,
        endDate: `${dateRange.endDate}T23:59:59.999Z`,
      });

      setStatistics(data);
    } catch (err) {
      console.error('Failed to load statistics:', err);
      if (err instanceof ApiClientError) {
        setError(err.message);
      } else {
        setError('加载统计数据失败');
      }
    } finally {
      setLoading(false);
    }
  };

  // 快捷时间范围
  const setQuickRange = (days: number) => {
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - days);
    setDateRange({
      startDate: start.toISOString().split('T')[0],
      endDate: end.toISOString().split('T')[0],
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <RefreshCw className="w-8 h-8 text-indigo-600 animate-spin mx-auto mb-4" />
          <p className="text-gray-500">{'加载中...'}</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 text-red-500 mx-auto mb-4" />
          <p className="text-gray-900 font-medium mb-2">{'加载失败'}</p>
          <p className="text-gray-500 mb-4">{error}</p>
          <button
            onClick={loadData}
            className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
          >
            {'重试'}
          </button>
        </div>
      </div>
    );
  }

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

  const maxDayCount = Math.max(...(statistics?.byDay.map((d) => d.count) || [1]));

  return (
    <div className="p-6 space-y-6">
      {/* 时间范围选择 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
        <div className="flex items-center justify-between flex-wrap gap-4">
          <div className="flex items-center space-x-2">
            <Calendar className="w-5 h-5 text-gray-400" />
            <span className="text-sm text-gray-500">{t.audit?.statistics?.timeRange}:</span>
            <input
              type="date"
              value={dateRange.startDate}
              onChange={(e) =>
                setDateRange((prev) => ({ ...prev, startDate: e.target.value }))
              }
              className="px-3 py-1.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
            />
            <span className="text-gray-400">{t.audit?.statistics?.to}</span>
            <input
              type="date"
              value={dateRange.endDate}
              onChange={(e) =>
                setDateRange((prev) => ({ ...prev, endDate: e.target.value }))
              }
              className="px-3 py-1.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
            />
          </div>
          <div className="flex items-center space-x-2">
            <span className="text-sm text-gray-500">{t.audit?.statistics?.quickSelect}:</span>
            <button
              onClick={() => setQuickRange(7)}
              className="px-3 py-1.5 text-sm border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
            >
              {t.audit?.statistics?.last7Days}
            </button>
            <button
              onClick={() => setQuickRange(30)}
              className="px-3 py-1.5 text-sm border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
            >
              {t.audit?.statistics?.last30Days}
            </button>
            <button
              onClick={() => setQuickRange(90)}
              className="px-3 py-1.5 text-sm border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
            >
              {t.audit?.statistics?.last90Days}
            </button>
          </div>
        </div>
      </div>

      {/* 概览卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        <StatCard
          title={'总操作数'}
          value={statistics?.summary.total || 0}
          icon={<BarChart3 className="w-5 h-5" />}
          color="indigo"
        />
        <StatCard
          title={'成功操作'}
          value={statistics?.summary.success || 0}
          icon={<CheckCircle className="w-5 h-5" />}
          color="green"
          subtitle={`${successRate}%`}
        />
        <StatCard
          title={'失败操作'}
          value={statistics?.summary.failed || 0}
          icon={<XCircle className="w-5 h-5" />}
          color="red"
        />
        <StatCard
          title={'财务操作'}
          value={statistics?.summary.financial || 0}
          icon={<TrendingUp className="w-5 h-5" />}
          color="emerald"
        />
        <StatCard
          title={'敏感操作'}
          value={statistics?.summary.sensitive || 0}
          icon={<AlertCircle className="w-5 h-5" />}
          color="amber"
        />
      </div>

      {/* 图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 每日趋势 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-gray-900">{t.audit?.statistics?.dailyTrend}</h3>
            <TrendingUp className="w-5 h-5 text-gray-400" />
          </div>
          <div className="space-y-3">
            {statistics?.byDay.map((item) => {
              const percentage = (item.count / maxDayCount) * 100;
              const date = new Date(item.date);
              const dateStr = date.toLocaleDateString('zh-CN', {
                month: 'short',
                day: 'numeric',
              });

              return (
                <div key={item.date} className="flex items-center">
                  <span className="w-16 text-sm text-gray-500">{dateStr}</span>
                  <div className="flex-1 mx-3">
                    <div className="w-full bg-gray-100 rounded-full h-6 relative">
                      <div
                        className="bg-gradient-to-r from-indigo-500 to-indigo-600 h-6 rounded-full transition-all duration-500 flex items-center justify-end pr-2"
                        style={{ width: `${Math.max(percentage, 5)}%` }}
                      >
                        {percentage > 20 && (
                          <span className="text-xs text-white font-medium">
                            {item.count}
                          </span>
                        )}
                      </div>
                      {percentage <= 20 && (
                        <span className="absolute right-2 top-1/2 transform -translate-y-1/2 text-xs text-gray-600 font-medium">
                          {item.count}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
            {(!statistics?.byDay || statistics.byDay.length === 0) && (
              <div className="py-8">
                <PageState
                  variant="empty"
                  title={t.audit?.empty?.noData || t.common.noData}
                  layout="center"
                  className="border-0 bg-transparent"
                />
              </div>
            )}
          </div>
        </div>

        {/* 模块分布 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-gray-900">{t.audit?.statistics?.moduleDistribution}</h3>
            <PieChart className="w-5 h-5 text-gray-400" />
          </div>
          <div className="space-y-4">
            {statistics?.byModule.map((item, index) => {
              const percentage = statistics.summary.total
                ? Math.round((item.count / statistics.summary.total) * 100)
                : 0;
              const colors = [
                'bg-indigo-500',
                'bg-blue-500',
                'bg-green-500',
                'bg-yellow-500',
                'bg-purple-500',
                'bg-pink-500',
                'bg-orange-500',
                'bg-cyan-500',
              ];
              const color = colors[index % colors.length];

              return (
                <div key={item.module}>
                  <div className="flex items-center justify-between text-sm mb-1">
                    <div className="flex items-center">
                      <div className={`w-3 h-3 rounded-full ${color} mr-2`} />
                      <span className="text-gray-700">
                        {formatModuleName(item.module)}
                      </span>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span className="text-gray-900 font-medium">{item.count}</span>
                      <span className="text-gray-400">({percentage}%)</span>
                    </div>
                  </div>
                  <div className="w-full bg-gray-100 rounded-full h-2 ml-5">
                    <div
                      className={`${color} h-2 rounded-full transition-all duration-500`}
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                </div>
              );
            })}
            {(!statistics?.byModule || statistics.byModule.length === 0) && (
              <div className="py-8">
                <PageState
                  variant="empty"
                  title={t.audit?.empty?.noData || t.common.noData}
                  layout="center"
                  className="border-0 bg-transparent"
                />
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 操作类型分布 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-lg font-semibold text-gray-900">{t.audit?.statistics?.actionDistribution}</h3>
          <BarChart3 className="w-5 h-5 text-gray-400" />
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
          {statistics?.byAction.map((item) => {
            const color = getActionColor(item.action);

            return (
              <div
                key={item.action}
                className={`p-4 rounded-lg border ${color.border} ${color.bg}`}
              >
                <div className={`text-2xl font-bold ${color.text}`}>
                  {item.count}
                </div>
                <div className={`text-sm ${color.text} mt-1`}>
                  {getActionLabel(item.action, t)}
                </div>
              </div>
            );
          })}
          {(!statistics?.byAction || statistics.byAction.length === 0) && (
            <div className="py-8 col-span-full">
              <PageState
                variant="empty"
                title={t.audit?.empty?.noData || t.common.noData}
                layout="center"
                className="border-0 bg-transparent"
              />
            </div>
          )}
        </div>
      </div>

      {/* 成功率详情 */}
      {statistics?.byModule && statistics.byModule.length > 0 && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-6">模块成功率</h3>
          <div className="overflow-x-auto">
            <table className="min-w-full">
              <thead>
                <tr className="border-b border-gray-100">
                  <th className="text-left py-3 px-4 text-sm font-medium text-gray-500">
                    模块
                  </th>
                  <th className="text-right py-3 px-4 text-sm font-medium text-gray-500">
                    操作数
                  </th>
                  <th className="text-right py-3 px-4 text-sm font-medium text-gray-500">
                    成功率
                  </th>
                  <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 w-48">
                    进度
                  </th>
                </tr>
              </thead>
              <tbody>
                {statistics.byModule.map((item) => (
                  <tr key={item.module} className="border-b border-gray-50">
                    <td className="py-3 px-4 text-sm text-gray-900">
                      {formatModuleName(item.module)}
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-900 text-right">
                      {item.count}
                    </td>
                    <td className="py-3 px-4 text-sm text-right">
                      <span
                        className={`font-medium ${
                          item.successRate >= 95
                            ? 'text-green-600'
                            : item.successRate >= 80
                            ? 'text-yellow-600'
                            : 'text-red-600'
                        }`}
                      >
                        {Math.round(item.successRate)}%
                      </span>
                    </td>
                    <td className="py-3 px-4">
                      <div className="w-full bg-gray-100 rounded-full h-2">
                        <div
                          className={`h-2 rounded-full transition-all duration-500 ${
                            item.successRate >= 95
                              ? 'bg-green-500'
                              : item.successRate >= 80
                              ? 'bg-yellow-500'
                              : 'bg-red-500'
                          }`}
                          style={{ width: `${item.successRate}%` }}
                        />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

/**
 * 统计卡片组件
 */
function StatCard({
  title,
  value,
  icon,
  color,
  subtitle,
}: {
  title: string;
  value: number;
  icon: React.ReactNode;
  color: 'indigo' | 'green' | 'red' | 'emerald' | 'amber';
  subtitle?: string;
}) {
  const colorClasses = {
    indigo: 'bg-indigo-50 text-indigo-600',
    green: 'bg-green-50 text-green-600',
    red: 'bg-red-50 text-red-600',
    emerald: 'bg-emerald-50 text-emerald-600',
    amber: 'bg-amber-50 text-amber-600',
  };

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm text-gray-500">{title}</p>
          <div className="flex items-baseline mt-1">
            <p className="text-2xl font-bold text-gray-900">
              {value.toLocaleString()}
            </p>
            {subtitle && (
              <span className="ml-2 text-sm text-gray-500">{subtitle}</span>
            )}
          </div>
        </div>
        <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${colorClasses[color]}`}>
          {icon}
        </div>
      </div>
    </div>
  );
}
