'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthGuard } from '@/hooks/useAuthGuard';
import { useSidebar } from '@/hooks/useSidebar';
import { useTranslation } from '@/hooks/useTranslation';
import { getApprovalStats } from '@/services/api/approval';
import {
  Clock,
  FileText,
  CheckCircle2,
  Mail,
  Plus,
  MessageSquare,
  ArrowRight,
} from 'lucide-react';

interface ApprovalStats {
  pendingCount: number;          // 待我处理
  urgentCount: number;           // 紧急任务
  overdueCount: number;          // 已逾期
  initiatedCount: number;        // 我创建的
  processedToday: number;        // 今日已处理
  processedThisWeek: number;     // 本周已处理
  ccUnreadCount: number;         // 抄送我的（未读）
}

export default function OverviewPage() {
  const router = useRouter();
  const { isReady, user } = useAuthGuard();
  const { collapsed } = useSidebar();
  const { t, locale } = useTranslation();
  const [stats, setStats] = useState<ApprovalStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    console.log('[Overview] useEffect triggered, isReady:', isReady);
    if (!isReady) {
      console.log('[Overview] Not ready yet, skipping data load');
      return;
    }
    console.log('[Overview] Ready, loading data...');
    loadOverviewData();
  }, [isReady]);

  const loadOverviewData = async () => {
    try {
      console.log('[Overview] Starting to load approval stats...');
      setLoading(true);
      
      // 使用封装好的 API 方法获取审批统计数据
      const statsData = await getApprovalStats();
      console.log('[Overview] Stats loaded:', statsData);
      setStats(statsData);
    } catch (error) {
      console.error('[Overview] Failed to load overview data:', error);
      // 设置默认值以避免页面崩溃
      setStats({
        pendingCount: 0,
        urgentCount: 0,
        overdueCount: 0,
        initiatedCount: 0,
        processedToday: 0,
        processedThisWeek: 0,
        ccUnreadCount: 0,
      });
    } finally {
      setLoading(false);
    }
  };

  // 加载状态
  if (!isReady || loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600 text-sm">{t.common.loading}</p>
        </div>
      </div>
    );
  }

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return t.dashboard.time.morning;
    if (hour < 18) return t.dashboard.time.afternoon;
    return t.dashboard.time.evening;
  };

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
      {/* 工具栏 - 现代飞书风格，标准 h-12 高度 */}
      <div className="bg-white border-b" style={{ borderColor: '#e5e6eb' }}>
        <div className="px-6 h-12">
          <div className="flex items-center justify-between h-full">
            <div className="flex items-center gap-3">
              {/* 欢迎信息 - 简洁版 */}
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium" style={{ color: '#1f2329' }}>
                  {getGreeting()}，{user?.displayName || user?.username}
                </span>
                <span className="text-xs" style={{ color: '#8f959e' }}>
                  {new Date().toLocaleDateString(locale === 'zh' ? 'zh-CN' : 'en-US', { 
                    month: 'short', 
                    day: 'numeric', 
                    weekday: 'short' 
                  })}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 内容区域 - flex-1 自动占满剩余空间 */}
      <div className="flex-1 overflow-auto">
        <div className="p-6 space-y-6">
          {/* 审批中心 - 待办事项 */}
          <section>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                {t.nav.approvals}
              </h2>
              <button
                onClick={() => router.push('/approval-center')}
                className="flex items-center gap-1 text-sm transition-colors"
                style={{ color: '#3370ff' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.color = '#1e5eff';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.color = '#3370ff';
                }}
              >
                <span>{t.dashboard.recentActivity.viewAll}</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 待我处理 */}
              <button
                onClick={() => router.push('/approval-center?tab=pending')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                {/* 背景装饰 */}
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(51, 112, 255, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  {/* 左侧：图标+名称 */}
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #3370ff 0%, #1e5eff 100%)' }}>
                      <Clock className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight max-w-[140px]" style={{ color: '#646a73' }}>
                      {t.approvals.pendingMyApproval}
                    </p>
                  </div>
                  {/* 右侧：数字 */}
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.pendingCount || 0}
                    </p>
                  </div>
                </div>
              </button>

              {/* 我创建的 */}
              <button
                onClick={() => router.push('/approval-center?tab=initiated')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                {/* 背景装饰 */}
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(0, 180, 42, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  {/* 左侧：图标+名称 */}
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #00b42a 0%, #009624 100%)' }}>
                      <FileText className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight max-w-[140px]" style={{ color: '#646a73' }}>
                      {t.approvals.myCreated}
                    </p>
                  </div>
                  {/* 右侧：数字 */}
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.initiatedCount || 0}
                    </p>
                  </div>
                </div>
              </button>

              {/* 我已处理 */}
              <button
                onClick={() => router.push('/approval-center?tab=processed')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                {/* 背景装饰 */}
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(151, 117, 250, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  {/* 左侧：图标+名称 */}
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #9775fa 0%, #7c5cdb 100%)' }}>
                      <CheckCircle2 className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight max-w-[140px]" style={{ color: '#646a73' }}>
                      {t.approvals.myProcessed}
                    </p>
                  </div>
                  {/* 右侧：数字 */}
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.processedToday || 0}
                    </p>
                  </div>
                </div>
              </button>

              {/* 抄送我的 */}
              <button
                onClick={() => router.push('/approval-center?tab=cc')}
                className="relative bg-white rounded-lg p-5 transition-all text-left group overflow-hidden"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                {/* 背景装饰 */}
                <div className="absolute -top-8 -right-8 w-32 h-32 rounded-full opacity-50 group-hover:scale-125 transition-transform duration-500" style={{ backgroundColor: 'rgba(255, 125, 0, 0.05)' }}></div>
                
                <div className="relative z-10 flex items-center justify-between h-full">
                  {/* 左侧：图标+名称 */}
                  <div className="flex flex-col items-start gap-3">
                    <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #ff7d00 0%, #e66a00 100%)' }}>
                      <Mail className="w-6 h-6 text-white" />
                    </div>
                    <p className="text-sm font-medium leading-tight max-w-[140px]" style={{ color: '#646a73' }}>
                      {t.approvals.ccToMe}
                    </p>
                  </div>
                  {/* 右侧：数字 */}
                  <div className="text-right">
                    <p className="text-3xl font-bold leading-none tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.ccUnreadCount || 0}
                    </p>
                  </div>
                </div>
              </button>
            </div>
          </section>

          {/* 快捷操作 */}
          <section>
            <h2 className="text-base font-semibold mb-4" style={{ color: '#1f2329' }}>
              {t.dashboard.quickActions.title}
            </h2>
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
              {/* 新建申请 */}
              <button
                onClick={() => router.push('/approval-center?tab=submit')}
                className="bg-white rounded-lg p-4 flex flex-col items-center gap-3 transition-all"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: '#f7f8fa' }}>
                  <Plus className="w-6 h-6" style={{ color: '#3370ff' }} />
                </div>
                <span className="text-sm font-medium" style={{ color: '#1f2329' }}>
                  {t.dashboard.quickActions.createRequest}
                </span>
              </button>

              {/* 反馈中心 */}
              <button
                onClick={() => router.push('/feedback')}
                className="bg-white rounded-lg p-4 flex flex-col items-center gap-3 transition-all"
                style={{ border: '1px solid #e5e6eb' }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                  e.currentTarget.style.borderColor = '#c9cdd4';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none';
                  e.currentTarget.style.borderColor = '#e5e6eb';
                }}
              >
                <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: '#f7f8fa' }}>
                  <MessageSquare className="w-6 h-6" style={{ color: '#ff7d00' }} />
                </div>
                <span className="text-sm font-medium" style={{ color: '#1f2329' }}>
                  {t.nav.feedback}
                </span>
              </button>
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}
