import React, { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Sidebar from '../components/Sidebar';
import { FileText, Layout, Plus, Settings, TrendingUp, ArrowRight } from 'lucide-react';
import { User, Report, Template } from '../types';
import { storage } from '../utils/storage';

export default function Dashboard() {
  const navigate = useNavigate();
  const [stats, setStats] = useState({
    totalCount: 0,
    monthCount: 0,
    templateCount: 0,
    userCount: 0,
    todayCount: 0,
    trend: [0,0,0,0,0,0,0],
    trendLabels: ['','','','','','',''],
    trendFullDates: ['','','','','','',''],
    maxTrend: 1
  });
  const [tooltip, setTooltip] = useState<{ visible: boolean; x: number; y: number; date: string; count: number }>({ visible: false, x: 0, y: 0, date: '', count: 0 });
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [timeRange, setTimeRange] = useState<'7days' | '1month'>('7days');

  useEffect(() => {
    const user = storage.get<User | null>('currentUser', null);
    if (!user) {
      navigate('/');
      return;
    }
    setCurrentUser(user);

    // Load stats
    const reports = storage.get<Report[]>('reports', []);
    const templates = storage.get<Template[]>('templates', []);
    const users = storage.get<User[]>('users', []);
    
    const userReports = user.role === 'user' 
        ? reports.filter(r => r.author === user.username)
        : reports;
    
    const now = new Date();
    const today = now.toISOString().split('T')[0];
    const todayReports = userReports.filter(r => r.createdAt === today);

    // 本月报告数
    const currentMonth = today.slice(0, 7);
    const thisMonthReports = userReports.filter(r => r.createdAt && r.createdAt.startsWith(currentMonth));

    // 动态趋势数据
    const daysCount = timeRange === '7days' ? 7 : 30;
    const trend: number[] = [];
    const labels: string[] = [];
    const fullDates: string[] = [];
    for (let i = daysCount - 1; i >= 0; i--) {
      const d = new Date(now);
      d.setDate(d.getDate() - i);
      const dateStr = d.toISOString().split('T')[0];
      const label = timeRange === '7days' ? `${d.getMonth() + 1}/${d.getDate()}` : `${d.getDate()}`;
      labels.push(label);
      fullDates.push(dateStr);
      trend.push(userReports.filter(r => r.createdAt === dateStr).length);
    }
    const maxTrend = Math.max(...trend, 1);

    setStats({
      totalCount: userReports.length,
      monthCount: thisMonthReports.length,
      templateCount: templates.length,
      userCount: users.length,
      todayCount: todayReports.length,
      trend,
      trendLabels: labels,
      trendFullDates: fullDates,
      maxTrend
    });
  }, [navigate, timeRange]);

  if (!currentUser) return null;

  return (
    <div className="flex min-h-screen bg-bg">
      <Sidebar />
      
      <main className="flex-1 p-10 overflow-y-auto">
        <header className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-2xl font-bold tracking-tight text-text-main">工作台概览</h1>
            <p className="text-text-muted text-sm mt-1">实时报告动态与系统状态追踪。</p>
          </div>
          <Link to="/report-editor" className="btn-accent inline-flex items-center gap-2">
            <Plus size={18} />
            新建报告
          </Link>
        </header>
        
        <section className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div className="card-minimal">
            <div className="text-[11px] text-text-muted mb-2 uppercase tracking-wider font-bold">全部报告总数</div>
            <div className="text-3xl font-bold text-text-main">{stats.totalCount}</div>
          </div>

          <div className="card-minimal">
            <div className="text-[11px] text-text-muted mb-2 uppercase tracking-wider font-bold">本月报告总数</div>
            <div className="text-3xl font-bold text-text-main">{stats.monthCount}</div>
          </div>

          <div className="card-minimal">
            <div className="text-[11px] text-text-muted mb-2 uppercase tracking-wider font-bold">今日新增报告</div>
            <div className="text-3xl font-bold text-text-main">{stats.todayCount}</div>
          </div>

          <div className="card-minimal">
            <div className="text-[11px] text-text-muted mb-2 uppercase tracking-wider font-bold">系统总用户</div>
            <div className="text-3xl font-bold text-text-main">{stats.userCount}</div>
          </div>
        </section>
        
        <div className="grid grid-cols-1 lg:grid-cols-[1.5fr_1fr] gap-6">
          <div className="card-minimal flex flex-col">
            <div className="flex justify-between items-center mb-6">
              <span className="font-bold text-sm uppercase tracking-wider text-text-main flex items-center gap-2">
                <TrendingUp size={16} className="text-accent" />
                报告增长趋势
              </span>
              <div className="flex bg-slate-100 p-1 rounded-lg">
                <button
                  onClick={() => setTimeRange('7days')}
                  className={`px-3 py-1 text-xs font-bold rounded-md transition-colors ${timeRange === '7days' ? 'bg-white text-accent shadow-sm' : 'text-text-muted hover:text-text-main'}`}
                >最近 7 天</button>
                <button
                  onClick={() => setTimeRange('1month')}
                  className={`px-3 py-1 text-xs font-bold rounded-md transition-colors ${timeRange === '1month' ? 'bg-white text-accent shadow-sm' : 'text-text-muted hover:text-text-main'}`}
                >最近 30 天</button>
              </div>
            </div>
            <div className="flex-1 bg-slate-50 rounded-xl p-6 min-h-[240px] relative">
              {/* SVG Area Chart */}
              <svg
                viewBox="0 0 300 135"
                className="w-full h-full overflow-visible"
                onMouseMove={(e) => {
                  const svg = e.currentTarget;
                  const rect = svg.getBoundingClientRect();
                  const mouseX = ((e.clientX - rect.left) / rect.width) * 300;
                  const paddingX = 10;
                  const chartW = 300 - paddingX * 2;
                  const n = stats.trend.length;
                  if (n <= 1) return;
                  let idx = Math.round(((mouseX - paddingX) / chartW) * (n - 1));
                  idx = Math.max(0, Math.min(n - 1, idx));
                  const ptX = paddingX + (idx / (n - 1)) * chartW;
                  const ptY = 8 + (120 - 16) - (stats.maxTrend > 0 ? (stats.trend[idx] / stats.maxTrend) * (120 - 16) : 0);
                  setTooltip({
                    visible: true,
                    x: (ptX / 300) * rect.width,
                    y: (ptY / 135) * rect.height,
                    date: stats.trendFullDates[idx] || '',
                    count: stats.trend[idx]
                  });
                }}
                onMouseLeave={() => setTooltip(prev => ({ ...prev, visible: false }))}
              >
                <defs>
                  <linearGradient id="trendGradient" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#2563EB" stopOpacity="0.35" />
                    <stop offset="100%" stopColor="#2563EB" stopOpacity="0.02" />
                  </linearGradient>
                </defs>
                {/* Grid lines */}
                {[0, 1, 2, 3].map((i) => (
                  <line
                    key={i}
                    x1="0"
                    y1={i * 30}
                    x2="300"
                    y2={i * 30}
                    stroke="#E2E8F0"
                    strokeWidth="1"
                    strokeDasharray="2 2"
                  />
                ))}
                {/* Area path */}
                {stats.trend.length > 0 && (() => {
                  const paddingX = 10;
                  const paddingY = 8;
                  const chartW = 300 - paddingX * 2;
                  const chartH = 120 - paddingY * 2;
                  const points = stats.trend.map((count, i) => {
                    const x = paddingX + (i / (stats.trend.length - 1)) * chartW;
                    const y = paddingY + chartH - (stats.maxTrend > 0 ? (count / stats.maxTrend) * chartH : 0);
                    return { x, y, count, label: stats.trendLabels[i] };
                  });
                  const linePath = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');
                  const areaPath = `${linePath} L ${points[points.length - 1].x} ${120 - paddingY} L ${points[0].x} ${120 - paddingY} Z`;
                  return (
                    <g>
                      <path d={areaPath} fill="url(#trendGradient)" />
                      <path d={linePath} fill="none" stroke="#2563EB" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                      {/* Transparent capture layer for reliable mouse events */}
                      <rect x="0" y="0" width="300" height="135" fill="transparent" />
                      {points.map((p, i) => (
                        <g key={i}>
                          {/* 7天模式显示圆点和数值；30天模式隐藏 */}
                          {stats.trend.length <= 10 && (
                            <>
                              <circle cx={p.x} cy={p.y} r="3.5" fill="#2563EB" stroke="#fff" strokeWidth="2" />
                              <text x={p.x} y={p.y - 10} textAnchor="middle" fontSize="8" fill="#64748B" fontWeight="bold">{p.count}</text>
                            </>
                          )}
                          {/* 标签稀疏化：7天每天显示，30天每隔5天显示 */}
                          {(stats.trend.length <= 10 || i % 5 === 0) && (
                            <text x={p.x} y={128} textAnchor="middle" fontSize={stats.trendLabels.length > 10 ? '7' : '8'} fill="#94A3B8" fontWeight="bold">{p.label}</text>
                          )}
                        </g>
                      ))}
                    </g>
                  );
                })()}
              </svg>
              {/* Tooltip */}
              {tooltip.visible && (
                <div
                  className="absolute pointer-events-none bg-slate-800 text-white text-xs rounded-lg px-3 py-2 shadow-lg z-10"
                  style={{ left: tooltip.x, top: tooltip.y - 40, transform: 'translateX(-50%)' }}
                >
                  <div className="font-bold">{tooltip.date}</div>
                  <div className="text-slate-300">报告数: {tooltip.count}</div>
                </div>
              )}
            </div>
          </div>

          <div className="card-minimal">
            <div className="font-bold text-sm uppercase tracking-wider text-text-main mb-6">快捷入口</div>
            <div className="space-y-2">
              <Link to="/report-manage" className="flex items-center justify-between p-4 bg-slate-50 rounded-xl hover:bg-white hover:shadow-md border border-transparent hover:border-border transition-all group">
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center text-text-muted group-hover:bg-accent group-hover:text-white transition-colors shadow-sm">
                    <FileText size={18} />
                  </div>
                  <div>
                    <div className="text-sm font-bold text-text-main">报告管理</div>
                    <div className="text-[11px] text-text-muted">查看与搜索所有报告</div>
                  </div>
                </div>
                <ArrowRight size={16} className="text-text-muted group-hover:text-accent group-hover:translate-x-1 transition-all" />
              </Link>
              
              {(currentUser.role === 'super' || currentUser.role === 'admin') && (
                <Link to="/template-manage" className="flex items-center justify-between p-4 bg-slate-50 rounded-xl hover:bg-white hover:shadow-md border border-transparent hover:border-border transition-all group">
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center text-text-muted group-hover:bg-accent group-hover:text-white transition-colors shadow-sm">
                      <Layout size={18} />
                    </div>
                    <div>
                      <div className="text-sm font-bold text-text-main">模板管理</div>
                      <div className="text-[11px] text-text-muted">配置报告标准模板</div>
                    </div>
                  </div>
                  <ArrowRight size={16} className="text-text-muted group-hover:text-accent group-hover:translate-x-1 transition-all" />
                </Link>
              )}

              {currentUser.role === 'super' && (
                <Link to="/system-settings" className="flex items-center justify-between p-4 bg-slate-50 rounded-xl hover:bg-white hover:shadow-md border border-transparent hover:border-border transition-all group">
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center text-text-muted group-hover:bg-accent group-hover:text-white transition-colors shadow-sm">
                      <Settings size={18} />
                    </div>
                    <div>
                      <div className="text-sm font-bold text-text-main">系统设置</div>
                      <div className="text-[11px] text-text-muted">配置抽帧与API参数</div>
                    </div>
                  </div>
                  <ArrowRight size={16} className="text-text-muted group-hover:text-accent group-hover:translate-x-1 transition-all" />
                </Link>
              )}
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
