'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts';
import { toast } from 'sonner';
import { TrendingUp, TrendingDown, Users, ShoppingCart, DollarSign, BookOpen, MessageCircle } from 'lucide-react';
import { API_BASE } from '@/lib/config';

interface OverviewData {
  users: { total: number; active: number; new: number; growth: number };
  orders: { total: number; today: number; growth: number };
  revenue: { total: number; today: number; growth: number };
  courses: { total: number };
  skills: { total: number };
}

interface TrendData {
  date: string;
  count?: number;
  revenue?: number;
}

export default function AnalyticsPage() {
  const router = useRouter();
  const [range, setRange] = useState('7d');
  const [overview, setOverview] = useState<OverviewData | null>(null);
  const [trend, setTrend] = useState<TrendData[]>([]);
  const [trendType, setTrendType] = useState('users');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, [range, trendType]);

  async function loadData() {
    setLoading(true);
    try {
      const token = localStorage.getItem('adminToken');
      const headers = { Authorization: `Bearer ${token}` };
      const base = API_BASE;

      const [ovRes, trRes] = await Promise.all([
        fetch(`${base}/admin/analytics/overview?range=${range}`, { headers }),
        fetch(`${base}/admin/analytics/trend?type=${trendType}&days=${range === 'today' ? 7 : range === '7d' ? 30 : 90}`, { headers }),
      ]);

      if (ovRes.ok) setOverview(await ovRes.json());
      if (trRes.ok) setTrend(await trRes.json());
    } catch {}
    setLoading(false);
  }

  function formatNumber(n: number) {
    if (n >= 10000) return (n / 10000).toFixed(1) + '万';
    return n.toString();
  }

  function formatDate(dateStr: string) {
    const d = new Date(dateStr);
    return `${d.getMonth() + 1}/${d.getDate()}`;
  }

  if (loading && !overview) {
    return (
      <div className="p-6 space-y-4">
        <div className="h-8 w-32 bg-muted animate-pulse rounded" />
        <div className="grid grid-cols-4 gap-4">
          {[1,2,3,4].map(i => <div key={i} className="h-24 bg-muted animate-pulse rounded-xl" />)}
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">数据统计分析</h1>
          <p className="text-sm text-muted-foreground">平台核心指标监控</p>
        </div>
        <select
          value={range}
          onChange={e => setRange(e.target.value)}
          className="px-3 py-2 border border-border rounded-lg bg-background text-foreground"
        >
          <option value="today">今日</option>
          <option value="7d">近7天</option>
          <option value="30d">近30天</option>
        </select>
      </div>

      {/* 核心指标 */}
      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <StatCard
          icon={<Users className="w-5 h-5" />}
          label="总用户"
          value={formatNumber(overview?.users.total || 0)}
          growth={overview?.users.growth}
          color="text-blue-600"
        />
        <StatCard
          icon={<Users className="w-5 h-5" />}
          label="活跃用户"
          value={formatNumber(overview?.users.active || 0)}
          color="text-green-600"
        />
        <StatCard
          icon={<ShoppingCart className="w-5 h-5" />}
          label="总订单"
          value={formatNumber(overview?.orders.total || 0)}
          color="text-purple-600"
        />
        <StatCard
          icon={<DollarSign className="w-5 h-5" />}
          label="总收入"
          value={formatNumber(overview?.revenue.total || 0)}
          growth={overview?.revenue.growth}
          color="text-orange-600"
          prefix="¥"
        />
        <StatCard
          icon={<BookOpen className="w-5 h-5" />}
          label="课程数"
          value={formatNumber(overview?.courses.total || 0)}
          color="text-indigo-600"
        />
        <StatCard
          icon={<MessageCircle className="w-5 h-5" />}
          label="技能数"
          value={formatNumber(overview?.skills.total || 0)}
          color="text-pink-600"
        />
      </div>

      {/* 趋势图 */}
      <div className="bg-card border border-border rounded-xl p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-foreground">趋势分析</h2>
          <div className="flex gap-2">
            {['users', 'orders', 'sessions'].map(t => (
              <button
                key={t}
                onClick={() => setTrendType(t)}
                className={`px-3 py-1 text-sm rounded-lg ${
                  trendType === t ? 'bg-brand-600 text-white' : 'bg-muted text-muted-foreground'
                }`}
              >
                {t === 'users' ? '用户' : t === 'orders' ? '订单' : '对话'}
              </button>
            ))}
          </div>
        </div>
        <div className="h-72">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={trend}>
              <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
              <XAxis dataKey="date" tickFormatter={formatDate} stroke="var(--muted-foreground)" fontSize={12} />
              <YAxis stroke="var(--muted-foreground)" fontSize={12} />
              <Tooltip
                contentStyle={{
                  backgroundColor: 'var(--card)',
                  border: '1px solid var(--border)',
                  borderRadius: '8px',
                }}
              />
              <Area
                type="monotone"
                dataKey={trendType === 'orders' ? 'revenue' : 'count'}
                stroke="#2563eb"
                fill="#3b82f620"
                strokeWidth={2}
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* 快捷操作 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <QuickAction
          label="用户分析"
          desc="查看用户增长趋势"
          onClick={() => { setTrendType('users'); setRange('30d'); }}
        />
        <QuickAction
          label="订单分析"
          desc="查看收入趋势"
          onClick={() => { setTrendType('orders'); setRange('30d'); }}
        />
        <QuickAction
          label="对话分析"
          desc="查看AI使用情况"
          onClick={() => { setTrendType('sessions'); setRange('30d'); }}
        />
        <QuickAction
          label="导出报告"
          desc="下载数据报表"
          onClick={() => toast.info('导出功能开发中')}
        />
      </div>
    </div>
  );
}

function StatCard({ icon, label, value, growth, color, prefix = '' }: any) {
  const isUp = growth > 0;
  return (
    <div className="bg-card border border-border rounded-xl p-4">
      <div className="flex items-center gap-2 mb-2">
        <span className={color}>{icon}</span>
        <span className="text-sm text-muted-foreground">{label}</span>
      </div>
      <div className="flex items-end justify-between">
        <div className="text-2xl font-bold text-foreground">{prefix}{value}</div>
        {growth !== undefined && (
          <div className={`flex items-center text-xs ${isUp ? 'text-green-600' : 'text-red-600'}`}>
            {isUp ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
            <span className="ml-0.5">{Math.abs(growth)}%</span>
          </div>
        )}
      </div>
    </div>
  );
}

function QuickAction({ label, desc, onClick }: any) {
  return (
    <button
      onClick={onClick}
      className="bg-card border border-border rounded-xl p-4 text-left hover:shadow-md hover:-translate-y-0.5 transition-all"
    >
      <div className="text-sm font-medium text-foreground">{label}</div>
      <div className="text-xs text-muted-foreground mt-1">{desc}</div>
    </button>
  );
}