'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslation } from '@/hooks/useTranslation';
import {
  Ticket,
  Plus,
  Clock,
  CheckCircle2,
  AlertCircle,
  TrendingUp,
  ChevronRight,
  Loader2,
  PlayCircle,
  List,
  ArrowRight,
} from 'lucide-react';
import { toast } from '@/lib/toast';
import {
  getTickets,
  getStatsOverview,
  TicketListItem,
  TicketStatus,
  StatsOverview,
  getStatusLabel,
  getStatusColor,
  getPriorityLabel,
  getPriorityColor,
  ApiClientError,
} from '@/services/api/tickets';

/**
 * 工单系统概览页
 * 遵循飞书风格设计规范
 */
export default function TicketsOverviewPage() {
  const router = useRouter();
  const { t } = useTranslation();
  
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<StatsOverview | null>(null);
  const [recentTickets, setRecentTickets] = useState<TicketListItem[]>([]);

  // 加载数据
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      
      // 并行加载统计和最近工单
      const [statsData, ticketsData] = await Promise.all([
        getStatsOverview().catch(() => null),
        getTickets({ limit: 5, sortBy: 'createdAt', sortOrder: 'desc' }),
      ]);
      
      if (statsData) {
        setStats(statsData);
      }
      setRecentTickets(ticketsData.items);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(error.message);
      } else {
        toast.error(t.common.loadFailed);
      }
    } finally {
      setLoading(false);
    }
  }, [t]);

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

  // 格式化时间
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 统计卡片配置
  const statCards = [
    {
      title: t.tickets?.stats?.total || '全部工单',
      value: stats?.total?.all ?? 0,
      icon: Ticket,
      bgColor: 'bg-blue-50',
      textColor: 'text-blue-600',
    },
    {
      title: t.tickets?.stats?.open || '待处理',
      value: stats?.total?.open ?? 0,
      icon: Clock,
      bgColor: 'bg-yellow-50',
      textColor: 'text-yellow-600',
    },
    {
      title: t.tickets?.stats?.inProgress || '处理中',
      value: stats?.total?.inProgress ?? 0,
      icon: PlayCircle,
      bgColor: 'bg-purple-50',
      textColor: 'text-purple-600',
    },
    {
      title: t.tickets?.stats?.resolved || '已解决',
      value: stats?.total?.resolved ?? 0,
      icon: CheckCircle2,
      bgColor: 'bg-green-50',
      textColor: 'text-green-600',
    },
  ];

  // 今日统计
  const todayStats = [
    {
      title: t.tickets?.stats?.todayCreated || '今日新建',
      value: stats?.today?.created ?? 0,
      icon: Plus,
      color: 'text-blue-600',
    },
    {
      title: t.tickets?.stats?.todayResolved || '今日解决',
      value: stats?.today?.resolved ?? 0,
      icon: CheckCircle2,
      color: 'text-green-600',
    },
    {
      title: t.tickets?.stats?.slaRate || 'SLA 达成率',
      value: `${((stats?.sla?.rate ?? 0) * 100).toFixed(1)}%`,
      icon: TrendingUp,
      color: stats?.sla?.rate && stats.sla.rate >= 0.9 ? 'text-green-600' : 'text-orange-600',
    },
    {
      title: t.tickets?.overview?.satisfaction || '满意度',
      value: stats?.satisfaction?.average ? `${stats.satisfaction.average.toFixed(1)}/5` : '-',
      icon: AlertCircle,
      color: 'text-blue-600',
    },
  ];

  // 快捷操作配置
  const quickActions = [
    {
      title: t.tickets?.create || '新建工单',
      description: t.tickets?.createDesc || '创建新的服务请求或问题报告',
      icon: Plus,
      bgColor: 'bg-blue-50',
      textColor: 'text-blue-600',
      action: () => router.push('/tickets/new'),
    },
    {
      title: t.tickets?.list?.title || '工单列表',
      description: t.tickets?.list?.desc || '查看和管理所有工单',
      icon: Ticket,
      bgColor: 'bg-green-50',
      textColor: 'text-green-600',
      action: () => router.push('/tickets/list'),
    },
  ];

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto" style={{ color: '#3370ff' }} />
          <p className="mt-4 text-sm" style={{ color: '#8f959e' }}>
            {t.tickets.overview.loading}
          </p>
        </div>
      </div>
    );
  }

  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">
              {/* 模块标识 */}
              <span className="text-sm font-medium" style={{ color: '#1f2329' }}>
                {t.tickets.title}
              </span>
            </div>
            
            {/* 新建工单按钮 */}
            <button
              onClick={() => router.push('/tickets/new')}
              className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium transition-all"
              style={{ 
                backgroundColor: '#3370ff',
                color: 'white'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#2b5dd1';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = '#3370ff';
              }}
            >
              <Plus className="w-4 h-4" />
              <span>{t.tickets.overview.newTicket}</span>
            </button>
          </div>
        </div>
      </div>

      {/* 内容区域 - flex-1 自动占满剩余空间 */}
      <div className="flex-1 overflow-auto">
        <div className="p-6 space-y-6">
          {/* 统计卡片 */}
          <section>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 全部工单 */}
              <div 
                className="bg-white rounded-lg p-5 transition-all cursor-pointer"
                style={{ border: '1px solid #e5e6eb' }}
                onClick={() => router.push('/tickets/list')}
                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="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium" style={{ color: '#646a73' }}>
                      {t.tickets.overview.allTickets}
                    </p>
                    <p className="mt-2 text-3xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.total?.all ?? 0}
                    </p>
                  </div>
                  <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'rgba(51, 112, 255, 0.1)' }}>
                    <Ticket className="w-6 h-6" style={{ color: '#3370ff' }} />
                  </div>
                </div>
              </div>

              {/* 待处理 */}
              <div 
                className="bg-white rounded-lg p-5 transition-all cursor-pointer"
                style={{ border: '1px solid #e5e6eb' }}
                onClick={() => router.push('/tickets/list?status=open')}
                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="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium" style={{ color: '#646a73' }}>
                      {t.tickets.overview.open}
                    </p>
                    <p className="mt-2 text-3xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.total?.open ?? 0}
                    </p>
                  </div>
                  <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'rgba(255, 125, 0, 0.1)' }}>
                    <Clock className="w-6 h-6" style={{ color: '#ff7d00' }} />
                  </div>
                </div>
              </div>

              {/* 处理中 */}
              <div 
                className="bg-white rounded-lg p-5 transition-all cursor-pointer"
                style={{ border: '1px solid #e5e6eb' }}
                onClick={() => router.push('/tickets/list?status=inProgress')}
                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="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium" style={{ color: '#646a73' }}>
                      {t.tickets.overview.inProgress}
                    </p>
                    <p className="mt-2 text-3xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.total?.inProgress ?? 0}
                    </p>
                  </div>
                  <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'rgba(151, 117, 250, 0.1)' }}>
                    <PlayCircle className="w-6 h-6" style={{ color: '#9775fa' }} />
                  </div>
                </div>
              </div>

              {/* 已解决 */}
              <div 
                className="bg-white rounded-lg p-5 transition-all cursor-pointer"
                style={{ border: '1px solid #e5e6eb' }}
                onClick={() => router.push('/tickets/list?status=resolved')}
                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="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium" style={{ color: '#646a73' }}>
                      {t.tickets.overview.resolved}
                    </p>
                    <p className="mt-2 text-3xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                      {stats?.total?.resolved ?? 0}
                    </p>
                  </div>
                  <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'rgba(0, 180, 42, 0.1)' }}>
                    <CheckCircle2 className="w-6 h-6" style={{ color: '#00b42a' }} />
                  </div>
                </div>
              </div>
            </div>
          </section>

          {/* 今日统计 */}
          <section>
            <h2 className="text-base font-semibold mb-4" style={{ color: '#1f2329' }}>
              {t.tickets.overview.todayStats}
            </h2>
            <div className="bg-white rounded-lg p-5" style={{ border: '1px solid #e5e6eb' }}>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                {/* 今日新建 */}
                <div className="text-center">
                  <div className="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center" style={{ backgroundColor: 'rgba(51, 112, 255, 0.1)' }}>
                    <Plus className="w-5 h-5" style={{ color: '#3370ff' }} />
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                    {stats?.today?.created ?? 0}
                  </p>
                  <p className="text-sm mt-1" style={{ color: '#646a73' }}>
                    {t.tickets.overview.todayCreated}
                  </p>
                </div>

                {/* 今日解决 */}
                <div className="text-center">
                  <div className="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center" style={{ backgroundColor: 'rgba(0, 180, 42, 0.1)' }}>
                    <CheckCircle2 className="w-5 h-5" style={{ color: '#00b42a' }} />
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                    {stats?.today?.resolved ?? 0}
                  </p>
                  <p className="text-sm mt-1" style={{ color: '#646a73' }}>
                    {t.tickets.overview.todayResolved}
                  </p>
                </div>

                {/* SLA 达成率 */}
                <div className="text-center">
                  <div className="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center" style={{ 
                    backgroundColor: stats?.sla?.rate && stats.sla.rate >= 0.9 
                      ? 'rgba(0, 180, 42, 0.1)' 
                      : 'rgba(255, 125, 0, 0.1)' 
                  }}>
                    <TrendingUp className="w-5 h-5" style={{ 
                      color: stats?.sla?.rate && stats.sla.rate >= 0.9 ? '#00b42a' : '#ff7d00' 
                    }} />
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                    {((stats?.sla?.rate ?? 0) * 100).toFixed(1)}%
                  </p>
                  <p className="text-sm mt-1" style={{ color: '#646a73' }}>
                    {t.tickets.overview.slaRate}
                  </p>
                </div>

                {/* 满意度 */}
                <div className="text-center">
                  <div className="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center" style={{ backgroundColor: 'rgba(51, 112, 255, 0.1)' }}>
                    <AlertCircle className="w-5 h-5" style={{ color: '#3370ff' }} />
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: '#1f2329' }}>
                    {stats?.satisfaction?.average ? `${stats.satisfaction.average.toFixed(1)}/5` : '-'}
                  </p>
                  <p className="text-sm mt-1" style={{ color: '#646a73' }}>
                    {t.tickets.overview.satisfaction}
                  </p>
                </div>
              </div>
            </div>
          </section>

          {/* 快捷操作 */}
          <section>
            <h2 className="text-base font-semibold mb-4" style={{ color: '#1f2329' }}>
              {t.tickets.overview.quickActions}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 我的工单 */}
              <button
                onClick={() => router.push('/tickets/my')}
                className="bg-white rounded-lg p-5 transition-all text-left"
                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="flex items-start gap-4">
                  <div className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0" style={{ backgroundColor: 'rgba(51, 112, 255, 0.1)' }}>
                    <Ticket className="w-6 h-6" style={{ color: '#3370ff' }} />
                  </div>
                  <div className="flex-1">
                    <h3 className="text-base font-semibold mb-1" style={{ color: '#1f2329' }}>
                      {t.tickets.overview.myTickets}
                    </h3>
                    <p className="text-sm" style={{ color: '#8f959e' }}>
                      {t.tickets.overview.myTicketsDesc}
                    </p>
                  </div>
                  <ArrowRight className="w-5 h-5 flex-shrink-0" style={{ color: '#c9cdd4' }} />
                </div>
              </button>

              {/* 工单列表 */}
              <button
                onClick={() => router.push('/tickets/list')}
                className="bg-white rounded-lg p-5 transition-all text-left"
                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="flex items-start gap-4">
                  <div className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0" style={{ backgroundColor: 'rgba(0, 180, 42, 0.1)' }}>
                    <List className="w-6 h-6" style={{ color: '#00b42a' }} />
                  </div>
                  <div className="flex-1">
                    <h3 className="text-base font-semibold mb-1" style={{ color: '#1f2329' }}>
                      {t.tickets.overview.ticketList}
                    </h3>
                    <p className="text-sm" style={{ color: '#8f959e' }}>
                      {t.tickets.overview.ticketListDesc}
                    </p>
                  </div>
                  <ArrowRight className="w-5 h-5 flex-shrink-0" style={{ color: '#c9cdd4' }} />
                </div>
              </button>
            </div>
          </section>

          {/* 最近工单 */}
          <section>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                {t.tickets.overview.recentTickets}
              </h2>
              <button
                onClick={() => router.push('/tickets/list')}
                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.tickets.overview.viewAll}</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            </div>
            
            <div className="bg-white rounded-lg" style={{ border: '1px solid #e5e6eb' }}>
              {recentTickets.length === 0 ? (
                <div className="p-12 text-center">
                  <div className="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center" style={{ backgroundColor: '#f7f8fa' }}>
                    <Ticket className="w-10 h-10" style={{ color: '#c9cdd4' }} />
                  </div>
                  <h3 className="text-base font-medium mb-1" style={{ color: '#646a73' }}>
                    {t.tickets.overview.noTickets}
                  </h3>
                  <p className="text-sm mb-4" style={{ color: '#8f959e' }}>
                    {t.tickets.overview.noTicketsDesc}
                  </p>
                  <button
                    onClick={() => router.push('/tickets/new')}
                    className="px-4 py-1.5 rounded-lg text-sm font-medium flex items-center gap-2 mx-auto"
                    style={{ 
                      backgroundColor: '#3370ff',
                      color: '#ffffff',
                      border: 'none'
                    }}
                  >
                    <Plus className="w-4 h-4" />
                    {t.tickets.overview.newTicket}
                  </button>
                </div>
              ) : (
                <div>
                  {recentTickets.map((ticket, index) => {
                    const statusColor = getStatusColor(ticket.status);
                    const priorityColor = getPriorityColor(ticket.priority);

                    return (
                      <div
                        key={ticket.id}
                        onClick={() => router.push(`/tickets/${ticket.id}`)}
                        className="p-4 hover:bg-gray-50 transition-colors cursor-pointer flex items-center gap-4"
                        style={{ 
                          borderBottom: index < recentTickets.length - 1 ? '1px solid #e5e6eb' : 'none'
                        }}
                      >
                        {/* 优先级指示条 */}
                        <div 
                          className="w-1 h-10 rounded-full flex-shrink-0" 
                          style={{ 
                            backgroundColor: priorityColor.bg.replace('50', '400').replace('bg-', '').replace('-', '#')
                          }} 
                        />

                        {/* 内容 */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-xs font-mono" style={{ color: '#8f959e' }}>
                              {ticket.ticketNo}
                            </span>
                            <h3 className="text-sm font-medium truncate" style={{ color: '#1f2329' }}>
                              {ticket.title}
                            </h3>
                            <span 
                              className="px-2 py-0.5 text-xs rounded-full flex-shrink-0"
                              style={{
                                backgroundColor: statusColor.bg.replace('bg-', '').includes('blue') ? 'rgba(51, 112, 255, 0.1)' :
                                  statusColor.bg.replace('bg-', '').includes('yellow') ? 'rgba(255, 125, 0, 0.1)' :
                                  statusColor.bg.replace('bg-', '').includes('purple') ? 'rgba(151, 117, 250, 0.1)' :
                                  statusColor.bg.replace('bg-', '').includes('green') ? 'rgba(0, 180, 42, 0.1)' : '#f7f8fa',
                                color: statusColor.text.replace('text-', '').includes('blue') ? '#3370ff' :
                                  statusColor.text.replace('text-', '').includes('yellow') ? '#ff7d00' :
                                  statusColor.text.replace('text-', '').includes('purple') ? '#9775fa' :
                                  statusColor.text.replace('text-', '').includes('green') ? '#00b42a' : '#646a73'
                              }}
                            >
                              {getStatusLabel(ticket.status, t)}
                            </span>
                          </div>
                          <div className="flex items-center gap-4 text-xs" style={{ color: '#8f959e' }}>
                            {ticket.category && <span>{ticket.category.name}</span>}
                            <span>{formatDate(ticket.createdAt)}</span>
                            {ticket.assignee && (
                              <span>{t.tickets.overview.assignee}: {ticket.assignee.displayName}</span>
                            )}
                          </div>
                        </div>

                        <ChevronRight className="w-5 h-5 flex-shrink-0" style={{ color: '#c9cdd4' }} />
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}
