'use client';
import { useState, useEffect, useRef } from 'react';
import { useUser } from './layout';
import { authFetch, STATUS_NAMES } from '@/lib/auth-client';

// 数字递增动画 Hook
function useCountUp(target, duration = 500) {
  const [value, setValue] = useState(0);
  const rafRef = useRef(null);

  useEffect(() => {
    if (target === 0) { setValue(0); return; }
    const startTime = performance.now();
    const animate = (now) => {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);
      // easeOutQuart
      const eased = 1 - Math.pow(1 - progress, 4);
      setValue(Math.round(eased * target));
      if (progress < 1) {
        rafRef.current = requestAnimationFrame(animate);
      }
    };
    rafRef.current = requestAnimationFrame(animate);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); };
  }, [target, duration]);

  return value;
}

function StatCard({ icon, label, value, colorClass }) {
  const animatedValue = useCountUp(value, 600);
  return (
    <div className="stat-card">
      <div className={`stat-icon ${colorClass}`}>
        <span>{icon}</span>
      </div>
      <div>
        <div className="stat-value">{animatedValue}</div>
        <div className="stat-label">{label}</div>
      </div>
    </div>
  );
}

export default function DashboardPage() {
  const user = useUser();
  const [contracts, setContracts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({ total: 0, pending: 0, approved: 0, rejected: 0 });

  useEffect(() => {
    loadContracts();
  }, []);

  const loadContracts = async () => {
    try {
      const res = await authFetch('/api/contracts?page_size=500');
      const data = await res.json();
      const list = data.contracts || [];
      setContracts(list);

      // 计算统计数据
      const total = list.length;
      const pending = list.filter(c =>
        ['pending_supervisor', 'pending_finance', 'pending_secretary'].includes(c.status)
      ).length;
      const approved = list.filter(c => c.status === 'approved').length;
      const rejected = list.filter(c => c.status === 'rejected').length;
      setStats({ total, pending, approved, rejected });
    } catch (err) {
      console.error('加载合同数据失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateStr) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString('zh-CN');
  };

  const formatMoney = (val) => {
    if (val == null) return '-';
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(val);
  };

  // 最近5条合同
  const recentContracts = contracts.slice(0, 5);

  if (loading) {
    return (
      <div className="loading-overlay">
        <div className="loading-spinner"></div>
      </div>
    );
  }

  return (
    <div className="animate-fadeIn">
      {/* 欢迎语 */}
      <div className="page-header">
        <div>
          <h1 className="page-title">
            {getGreeting()}，{user?.real_name || '用户'} 👋
          </h1>
          <p className="page-subtitle">欢迎回到合同流转审批系统，以下是您的工作概况</p>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="stats-grid">
        <StatCard icon="📋" label="合同总数" value={stats.total} colorClass="blue" />
        <StatCard icon="⏳" label="待审批" value={stats.pending} colorClass="orange" />
        <StatCard icon="✅" label="已通过" value={stats.approved} colorClass="green" />
        <StatCard icon="❌" label="已驳回" value={stats.rejected} colorClass="red" />
      </div>

      {/* 最近合同 */}
      <div className="card">
        <div className="card-header">
          <h2 className="card-title">📄 最近合同</h2>
          <a href="/dashboard/contracts" className="btn btn-outline btn-sm">
            查看全部 →
          </a>
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          {recentContracts.length === 0 ? (
            <div className="empty-state">
              <div className="empty-state-icon">📭</div>
              <p className="empty-state-text">暂无合同数据</p>
            </div>
          ) : (
            <div className="table-container">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>项目名称</th>
                    <th>合作单位</th>
                    <th>合同金额</th>
                    <th>经办日期</th>
                    <th>状态</th>
                  </tr>
                </thead>
                <tbody>
                  {recentContracts.map((c) => (
                    <tr key={c.id}>
                      <td>
                        <a href={`/dashboard/contracts/${c.id}`} style={{ fontWeight: 500 }}>
                          {c.project_name || '-'}
                        </a>
                      </td>
                      <td>{c.partner_name || '-'}</td>
                      <td style={{ fontWeight: 600, color: 'var(--primary-dark)' }}>
                        {formatMoney(c.contract_amount)}
                      </td>
                      <td>{formatDate(c.created_at)}</td>
                      <td>
                        <span className={`status-badge status-${c.status}`}>
                          {STATUS_NAMES[c.status] || c.status}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function getGreeting() {
  const hour = new Date().getHours();
  if (hour < 6) return '夜深了';
  if (hour < 9) return '早上好';
  if (hour < 12) return '上午好';
  if (hour < 14) return '中午好';
  if (hour < 18) return '下午好';
  return '晚上好';
}
