'use client';

import { useEffect, useState } from 'react';
import {
  BarChart3,
  TrendingUp,
  Users,
  FileText,
  Clock,
  CheckCircle2,
  TrendingDown,
  Activity,
  Layers,
} from 'lucide-react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { toast } from '@/lib/toast';
import { PageState } from '@/components/common/feedback/PageState';
import { useTranslation } from '@/hooks/useTranslation';
import {
  getFormStatistics,
  formatProcessingTime,
  type FormStatistics as FormStatsType,
  type FormSubmissionTrend,
  type TopForm,
  type CategoryDistribution,
} from '@/services/api/form-statistics';
import { ApiClientError } from '@/lib/api-client';

export default function FormStatisticsPage() {
  const { t } = useTranslation();
  const [timeRange, setTimeRange] = useState<'7d' | '30d' | '90d' | '1y'>('30d');
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<FormStatsType | null>(null);
  const [trends, setTrends] = useState<FormSubmissionTrend[]>([]);
  const [topForms, setTopForms] = useState<TopForm[]>([]);
  const [categoryDistribution, setCategoryDistribution] = useState<CategoryDistribution[]>([]);

  // 加载统计数据
  useEffect(() => {
    loadStatistics();
  }, [timeRange]);

  const loadStatistics = async () => {
    try {
      setLoading(true);
      const data = await getFormStatistics(timeRange);
      setStats(data.stats);
      setTrends(data.trends);
      setTopForms(data.topForms);
      setCategoryDistribution(data.categoryDistribution);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`加载统计数据失败: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  // 图表颜色
  const COLORS = ['#3370ff', '#00c48c', '#ff6b6b', '#ffa94d', '#9775fa', '#20c997'];

  // 计算趋势变化
  const calculateTrend = (current: number, previous: number) => {
    if (previous === 0) return 0;
    return Math.round(((current - previous) / previous) * 100);
  };

  return (
    <div className="p-8 space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            {'统计分析'}
          </h1>
          <p className="text-sm text-gray-600 mt-1">
            {'表单使用情况和数据分析'}
          </p>
        </div>
        <Select value={timeRange} onValueChange={(v) => setTimeRange(v as any)}>
          <SelectTrigger className="w-32">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="7d">最近 7 天</SelectItem>
            <SelectItem value="30d">最近 30 天</SelectItem>
            <SelectItem value="90d">最近 90 天</SelectItem>
            <SelectItem value="1y">最近 1 年</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {/* 总表单数 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-gray-600">总表单数</span>
            <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <Layers className="w-5 h-5 text-blue-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-gray-900">
            {loading ? '-' : stats?.totalForms || 0}
          </div>
          <div className="flex items-center text-sm text-gray-500 mt-2">
            <Activity className="w-4 h-4 mr-1" />
            <span>已发布 {stats?.activeForms || 0} 个</span>
          </div>
        </div>

        {/* 总提交数 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-gray-600">总提交数</span>
            <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
              <FileText className="w-5 h-5 text-purple-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-gray-900">
            {loading ? '-' : stats?.totalSubmissions || 0}
          </div>
          <div className="flex items-center text-sm text-gray-500 mt-2">
            <Clock className="w-4 h-4 mr-1" />
            <span>{timeRange === '7d' ? '最近7天' : timeRange === '30d' ? '最近30天' : timeRange === '90d' ? '最近90天' : '最近1年'}</span>
          </div>
        </div>

        {/* 审批通过率 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-gray-600">审批通过率</span>
            <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
              <CheckCircle2 className="w-5 h-5 text-green-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-gray-900">
            {loading ? '-' : `${stats?.approvalRate || 0}%`}
          </div>
          <div className="flex items-center text-sm text-green-600 mt-2">
            <TrendingUp className="w-4 h-4 mr-1" />
            <span>保持稳定</span>
          </div>
        </div>

        {/* 平均处理时间 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-gray-600">平均处理时间</span>
            <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
              <Clock className="w-5 h-5 text-orange-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-gray-900">
            {loading ? '-' : stats?.avgProcessingTime || '-'}
          </div>
          <div className="flex items-center text-sm text-gray-500 mt-2">
            <Activity className="w-4 h-4 mr-1" />
            <span>审批周期</span>
          </div>
        </div>
      </div>

      {/* 热门表单排行 */}
      <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div className="flex items-center gap-2 mb-4">
          <BarChart3 className="w-5 h-5 text-blue-600" />
          <h2 className="text-lg font-semibold text-gray-900">热门表单排行</h2>
        </div>
        {loading ? (
          <div className="space-y-3">
            {[1, 2, 3, 4, 5].map((i) => (
              <div key={i} className="h-16 bg-gray-50 rounded-lg animate-pulse" />
            ))}
          </div>
        ) : topForms.length === 0 ? (
          <div className="py-8">
            <PageState
              variant="empty"
              title={t.common.noData}
              layout="center"
              className="border-0 bg-transparent"
            />
          </div>
        ) : (
          <div className="space-y-3">
            {topForms.slice(0, 5).map((form, index) => (
              <div key={form.formDefinitionId} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                <div className="flex items-center gap-3 flex-1">
                  <div className={`w-8 h-8 rounded-lg flex items-center justify-center font-semibold shrink-0 ${
                    index === 0 ? 'bg-yellow-100 text-yellow-700' :
                    index === 1 ? 'bg-gray-200 text-gray-700' :
                    index === 2 ? 'bg-orange-100 text-orange-700' :
                    'bg-blue-100 text-blue-700'
                  }`}>
                    {index + 1}
                  </div>
                  <div className="flex-1 min-w-0">
                    <span className="font-medium text-gray-900 truncate block">{form.formName}</span>
                    <span className="text-xs text-gray-500">通过率 {form.approvalRate}%</span>
                  </div>
                </div>
                <div className="flex items-center gap-6 shrink-0">
                  <div className="text-right">
                    <div className="text-sm font-medium text-gray-900">{form.submissions}</div>
                    <div className="text-xs text-gray-500">次提交</div>
                  </div>
                  <div className="text-right">
                    <div className="text-sm font-medium text-gray-600">{formatProcessingTime(form.avgProcessingTime)}</div>
                    <div className="text-xs text-gray-500">平均时长</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 提交趋势图表 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <h3 className="font-semibold text-gray-900 mb-4">提交趋势</h3>
          {loading ? (
            <div className="h-64 flex items-center justify-center bg-gray-50 rounded-lg">
              <p className="text-gray-500">{t.common.loading}</p>
            </div>
          ) : trends.length === 0 ? (
            <div className="h-64 flex items-center justify-center bg-gray-50 rounded-lg">
              <PageState
                variant="empty"
                title={t.common.noData}
                layout="center"
                className="border-0 bg-transparent"
              />
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={trends}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis 
                  dataKey="date" 
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => {
                    const date = new Date(value);
                    return `${date.getMonth() + 1}/${date.getDate()}`;
                  }}
                />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: '#fff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
                  }}
                  labelFormatter={(value) => {
                    const date = new Date(value);
                    return date.toLocaleDateString('zh-CN');
                  }}
                />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="submissions" 
                  stroke="#3370ff" 
                  strokeWidth={2}
                  name="提交数"
                  dot={{ fill: '#3370ff', r: 3 }}
                  activeDot={{ r: 5 }}
                />
                <Line 
                  type="monotone" 
                  dataKey="approvals" 
                  stroke="#00c48c" 
                  strokeWidth={2}
                  name="通过数"
                  dot={{ fill: '#00c48c', r: 3 }}
                  activeDot={{ r: 5 }}
                />
                <Line 
                  type="monotone" 
                  dataKey="rejections" 
                  stroke="#ff6b6b" 
                  strokeWidth={2}
                  name="驳回数"
                  dot={{ fill: '#ff6b6b', r: 3 }}
                  activeDot={{ r: 5 }}
                />
              </LineChart>
            </ResponsiveContainer>
          )}
        </div>
        
        {/* 分类分布图表 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <h3 className="font-semibold text-gray-900 mb-4">分类分布</h3>
          {loading ? (
            <div className="h-64 flex items-center justify-center bg-gray-50 rounded-lg">
              <p className="text-gray-500">{t.common.loading}</p>
            </div>
          ) : categoryDistribution.length === 0 ? (
            <div className="h-64 flex items-center justify-center bg-gray-50 rounded-lg">
              <PageState
                variant="empty"
                title={t.common.noData}
                layout="center"
                className="border-0 bg-transparent"
              />
            </div>
          ) : (
            <div className="flex items-center gap-6">
              <ResponsiveContainer width="50%" height={300}>
                <PieChart>
                  <Pie
                    data={categoryDistribution as any[]}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="count"
                  >
                    {categoryDistribution.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip 
                    contentStyle={{ 
                      backgroundColor: '#fff',
                      border: '1px solid #e5e7eb',
                      borderRadius: '8px',
                      boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
                    }}
                  />
                </PieChart>
              </ResponsiveContainer>
              <div className="flex-1 space-y-2">
                {categoryDistribution.map((item, index) => (
                  <div key={item.category} className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div 
                        className="w-3 h-3 rounded-sm"
                        style={{ backgroundColor: COLORS[index % COLORS.length] }}
                      />
                      <span className="text-sm text-gray-700">{item.category}</span>
                    </div>
                    <div className="text-sm font-medium text-gray-900">
                      {item.count} ({item.percentage}%)
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
