'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { 
  Package, 
  MapPin, 
  Clock,
  FileText,
  ArrowRight,
  Loader2,
  Plus,
  ChevronDown,
  ChevronUp,
  Phone,
  Mail,
  User,
  MessageSquare,
  Truck,
  CheckCircle,
  AlertCircle,
  Hourglass,
  Send,
  Sparkles,
  ClipboardCheck,
  PenTool,
  ExternalLink,
  Bell,
  BellRing
} from 'lucide-react';
import { useUser } from '@/contexts/user-context';
import { useLanguage } from '@/i18n/LanguageContext';
import { LanguageSwitcherSimple } from '@/components/language-switcher';
import ChatBox from '@/components/chat-box';

interface Order {
  id: string;
  order_number: string;
  customer_id: string | null;
  contact_name: string;
  contact_phone: string;
  contact_email: string | null;
  origin_city: string;
  destination_city: string;
  customs_city: string;
  status: string;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface UnreadInfo {
  orderId: string;
  unreadCount: number;
}

// 状态配置：颜色、图标、渐变
const statusConfig: Record<string, { 
  bg: string; 
  text: string; 
  gradient: string;
  icon: typeof Package;
  dotColor: string;
  labelZh: string;
  labelRu: string;
}> = {
  '新询价': { 
    bg: 'bg-blue-50', 
    text: 'text-blue-700', 
    gradient: 'from-blue-500 to-blue-600',
    icon: Send,
    dotColor: 'bg-blue-500',
    labelZh: '新询价',
    labelRu: 'Новый запрос'
  },
  '待确认': { 
    bg: 'bg-amber-50', 
    text: 'text-amber-700', 
    gradient: 'from-amber-500 to-orange-500',
    icon: Hourglass,
    dotColor: 'bg-amber-500',
    labelZh: '待确认',
    labelRu: 'Ожидает'
  },
  '装车方案设计中': { 
    bg: 'bg-cyan-50', 
    text: 'text-cyan-700', 
    gradient: 'from-cyan-500 to-teal-500',
    icon: PenTool,
    dotColor: 'bg-cyan-500',
    labelZh: '装车方案设计中',
    labelRu: 'Разработка плана'
  },
  '确认': { 
    bg: 'bg-green-50', 
    text: 'text-green-700', 
    gradient: 'from-green-500 to-emerald-500',
    icon: CheckCircle,
    dotColor: 'bg-green-500',
    labelZh: '确认',
    labelRu: 'Подтвержден'
  },
  '运输中（中国境内）': { 
    bg: 'bg-indigo-50', 
    text: 'text-indigo-700', 
    gradient: 'from-indigo-500 to-blue-500',
    icon: Truck,
    dotColor: 'bg-indigo-500',
    labelZh: '运输中（中国境内）',
    labelRu: 'В пути (Китай)'
  },
  '满洲里仓储中': { 
    bg: 'bg-violet-50', 
    text: 'text-violet-700', 
    gradient: 'from-violet-500 to-purple-500',
    icon: Package,
    dotColor: 'bg-violet-500',
    labelZh: '满洲里仓储中',
    labelRu: 'Склад в Маньчжурии'
  },
  '清关未完成': { 
    bg: 'bg-orange-50', 
    text: 'text-orange-700', 
    gradient: 'from-orange-500 to-red-500',
    icon: AlertCircle,
    dotColor: 'bg-orange-500',
    labelZh: '清关未完成',
    labelRu: 'На таможне'
  },
  '运输中（俄罗斯境内）': { 
    bg: 'bg-purple-50', 
    text: 'text-purple-700', 
    gradient: 'from-purple-500 to-violet-500',
    icon: Truck,
    dotColor: 'bg-purple-500',
    labelZh: '运输中（俄罗斯境内）',
    labelRu: 'В пути (Россия)'
  },
  '配送完成': { 
    bg: 'bg-emerald-50', 
    text: 'text-emerald-700', 
    gradient: 'from-emerald-500 to-teal-500',
    icon: Sparkles,
    dotColor: 'bg-emerald-500',
    labelZh: '配送完成',
    labelRu: 'Доставлен'
  },
};

export default function OrdersPage() {
  const { t, locale } = useLanguage();
  const { isLoading: userLoading } = useUser();
  const [orders, setOrders] = useState<Order[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [confirmingId, setConfirmingId] = useState<string | null>(null);
  const [unreadCounts, setUnreadCounts] = useState<Record<string, number>>({});
  const [totalUnread, setTotalUnread] = useState(0);

  useEffect(() => {
    if (userLoading) return;
    
    const fetchOrders = async () => {
      try {
        const response = await fetch('/api/orders');
        const data = await response.json();
        if (response.ok) {
          setOrders(data.orders || []);
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrders();
  }, [userLoading]);

  // 获取未读消息数
  const fetchUnreadCounts = async () => {
    if (orders.length === 0) return;
    try {
      const response = await fetch('/api/orders/unread-count');
      const data = await response.json();
      if (response.ok) {
        const counts: Record<string, number> = {};
        let total = 0;
        (data.unreadOrders || []).forEach((item: UnreadInfo) => {
          counts[item.orderId] = item.unreadCount;
          total += item.unreadCount;
        });
        setUnreadCounts(counts);
        setTotalUnread(total);
      }
    } catch (error) {
      console.error('Error fetching unread counts:', error);
    }
  };

  useEffect(() => {
    if (userLoading || orders.length === 0) return;

    fetchUnreadCounts();
    // 每30秒刷新一次未读消息数
    const interval = setInterval(fetchUnreadCounts, 30000);
    return () => clearInterval(interval);
  }, [userLoading, orders]);

  // 确认订单
  const handleConfirmOrder = async (orderId: string) => {
    setConfirmingId(orderId);
    try {
      const response = await fetch(`/api/orders/${orderId}/confirm`, {
        method: 'POST',
      });
      const data = await response.json();
      
      if (response.ok && data.success) {
        // 更新本地订单状态
        setOrders(prev => prev.map(order => 
          order.id === orderId 
            ? { ...order, status: '确认', updated_at: new Date().toISOString() }
            : order
        ));
      } else {
        alert(data.error || '确认失败，请稍后重试');
      }
    } catch (error) {
      console.error('Error confirming order:', error);
      alert('确认失败，请稍后重试');
    } finally {
      setConfirmingId(null);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  };

  const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 计算各状态订单数量
  const statusCounts = orders.reduce((acc, order) => {
    acc[order.status] = (acc[order.status] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  if (isLoading || userLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto">
      {/* 页面标题 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-gray-900">{t.user.orders}</h1>
            {totalUnread > 0 && (
              <span className="inline-flex items-center gap-1.5 px-3 py-1 bg-red-50 text-red-600 text-sm font-medium rounded-full border border-red-200">
                <BellRing className="w-4 h-4" />
                {totalUnread} {t.order.newMessages}
              </span>
            )}
          </div>
          <p className="text-gray-500 mt-1">{t.user.ordersDesc}</p>
        </div>
        <Link
          href="/#order"
          className="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-medium rounded-xl hover:shadow-lg hover:shadow-blue-500/25 hover:-translate-y-0.5 transition-all"
        >
          <Plus className="w-4 h-4" />
          {t.user.newInquiry}
        </Link>
      </div>

      {/* 订单统计卡片 */}
      {orders.length > 0 && (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mb-8">
          {Object.entries(statusConfig).map(([status, config]) => {
            const count = statusCounts[status] || 0;
            const Icon = config.icon;
            return (
              <div
                key={status}
                className={`relative overflow-hidden rounded-xl p-4 ${config.bg} border border-white/50`}
              >
                <div className={`absolute top-0 right-0 w-16 h-16 bg-gradient-to-br ${config.gradient} opacity-10 rounded-full -translate-y-4 translate-x-4`}></div>
                <div className="relative">
                  <div className="flex items-center gap-2 mb-2">
                    <Icon className={`w-4 h-4 ${config.text}`} />
                    <span className={`text-xs font-medium ${config.text}`}>{locale === 'zh' ? config.labelZh : config.labelRu}</span>
                  </div>
                  <div className={`text-2xl font-bold ${config.text}`}>{count}</div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* 订单列表 */}
      {orders.length === 0 ? (
        <div className="bg-gradient-to-br from-gray-50 to-blue-50/30 rounded-2xl p-12 border border-gray-200 text-center">
          <div className="w-20 h-20 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <Package className="w-10 h-10 text-blue-400" />
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">{t.order.noOrders}</h3>
          <p className="text-gray-500 mb-6">{t.order.noOrdersDesc}</p>
          <Link
            href="/#order"
            className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-medium rounded-xl hover:shadow-lg hover:shadow-blue-500/25 transition-all"
          >
            {t.home.inquiryNow}
            <ArrowRight className="w-4 h-4" />
          </Link>
        </div>
      ) : (
        <div className="space-y-4">
          {orders.map((order, index) => {
            const config = statusConfig[order.status] || statusConfig['新询价'];
            const StatusIcon = config.icon;
            const isExpanded = expandedId === order.id;
            const needsConfirm = order.status === '待确认';
            
            return (
              <div 
                key={order.id} 
                className={`bg-white rounded-2xl border overflow-hidden hover:shadow-lg hover:shadow-gray-200/50 transition-all duration-300 ${
                  needsConfirm 
                    ? 'border-amber-300 ring-2 ring-amber-100' 
                    : 'border-gray-100'
                }`}
              >
                {/* 订单卡片头部 */}
                <div 
                  className="flex flex-col md:flex-row md:items-center gap-4 p-5 cursor-pointer"
                  onClick={() => setExpandedId(isExpanded ? null : order.id)}
                >
                  {/* 左侧：订单号和路线 */}
                  <div className="flex-1 flex flex-col md:flex-row md:items-center gap-4">
                    {/* 订单号 */}
                    <div className="flex items-center gap-3">
                      <div className={`w-10 h-10 rounded-xl bg-gradient-to-br ${config.gradient} flex items-center justify-center shadow-sm`}>
                        <StatusIcon className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <div className="text-xs text-gray-400">{t.order.orderNumber}</div>
                          {unreadCounts[order.id] > 0 && (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-red-500 text-white text-xs font-medium rounded-full animate-pulse">
                              <Bell className="w-3 h-3" />
                              {unreadCounts[order.id]}
                            </span>
                          )}
                        </div>
                        <div className="font-mono text-sm font-semibold text-gray-900">
                          {order.order_number}
                        </div>
                      </div>
                    </div>

                    {/* 路线 */}
                    <div className="flex items-center gap-3 px-4 py-2 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl">
                      <div className="text-center">
                        <div className="text-xs text-gray-400 mb-0.5">{t.order.origin}</div>
                        <div className="font-medium text-gray-900 text-sm">{order.origin_city}</div>
                      </div>
                      <div className="flex items-center gap-1 text-blue-400">
                        <div className="w-4 h-px bg-blue-300"></div>
                        <ArrowRight className="w-4 h-4" />
                        <div className="w-4 h-px bg-blue-300"></div>
                      </div>
                      <div className="text-center">
                        <div className="text-xs text-gray-400 mb-0.5">{t.order.destination}</div>
                        <div className="font-medium text-gray-900 text-sm">{order.destination_city}</div>
                      </div>
                    </div>
                  </div>

                  {/* 右侧：状态、日期、操作 */}
                  <div className="flex items-center justify-between md:justify-end gap-4">
                    {/* 状态 */}
                    <div className="flex items-center gap-2">
                      <div className={`w-2 h-2 rounded-full ${config.dotColor} animate-pulse`}></div>
                      <span className={`inline-flex items-center px-3 py-1.5 rounded-lg text-xs font-semibold ${config.bg} ${config.text}`}>
                        {locale === 'zh' ? config.labelZh : config.labelRu}
                      </span>
                    </div>
                    
                    {/* 创建日期 */}
                    <div className="hidden sm:flex items-center gap-1.5 text-sm text-gray-500">
                      <Clock className="w-4 h-4 text-gray-300" />
                      {formatDate(order.created_at)}
                    </div>
                    
                    {/* 查看详情按钮 - 新标签页打开 */}
                    <button 
                      className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
                      onClick={(e) => {
                        e.stopPropagation();
                        window.open(`/user/orders/${order.order_number}`, '_blank');
                      }}
                    >
                      {t.order.detail}
                      <ExternalLink className="w-3.5 h-3.5" />
                    </button>
                    
                    {/* 展开/收起按钮 */}
                    <button 
                      className={`flex items-center gap-1 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors ${
                        isExpanded 
                          ? 'bg-blue-100 text-blue-700' 
                          : 'bg-gray-100 text-gray-600 hover:bg-blue-50 hover:text-blue-600'
                      }`}
                      onClick={(e) => {
                        e.stopPropagation();
                        setExpandedId(isExpanded ? null : order.id);
                      }}
                    >
                      {isExpanded ? (
                        <>
                          {t.order.collapse}
                          <ChevronUp className="w-4 h-4" />
                        </>
                      ) : (
                        <>
                          {t.order.detail}
                          <ChevronDown className="w-4 h-4" />
                        </>
                      )}
                    </button>
                  </div>
                </div>

                {/* 展开的详情内容 */}
                {isExpanded && (
                  <div className="border-t border-gray-100 bg-gradient-to-b from-gray-50/80 to-white">
                    <div className="p-5">
                      {/* 订单信息网格 */}
                      <div className="grid md:grid-cols-3 gap-6 mb-6">
                        {/* 联系人信息 */}
                        <div className="bg-white rounded-xl p-4 border border-gray-100 shadow-sm">
                          <h4 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                            <div className="w-6 h-6 bg-blue-100 rounded-lg flex items-center justify-center">
                              <User className="w-3.5 h-3.5 text-blue-600" />
                            </div>
                            {t.order.contactInfo}
                          </h4>
                          <div className="space-y-2.5 text-sm">
                            <div className="flex items-center gap-2 text-gray-600">
                              <User className="w-3.5 h-3.5 text-gray-300" />
                              <span>{order.contact_name}</span>
                            </div>
                            <div className="flex items-center gap-2 text-gray-600">
                              <Phone className="w-3.5 h-3.5 text-gray-300" />
                              <span>{order.contact_phone}</span>
                            </div>
                            {order.contact_email && (
                              <div className="flex items-center gap-2 text-gray-600">
                                <Mail className="w-3.5 h-3.5 text-gray-300" />
                                <span>{order.contact_email}</span>
                              </div>
                            )}
                          </div>
                        </div>

                        {/* 运输信息 */}
                        <div className="bg-white rounded-xl p-4 border border-gray-100 shadow-sm">
                          <h4 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                            <div className="w-6 h-6 bg-green-100 rounded-lg flex items-center justify-center">
                              <MapPin className="w-3.5 h-3.5 text-green-600" />
                            </div>
                            {t.order.transportInfo}
                          </h4>
                          <div className="space-y-2.5 text-sm">
                            <div className="flex items-center justify-between">
                              <span className="text-gray-400">{t.order.originCity}</span>
                              <span className="font-medium text-gray-900">{order.origin_city}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-gray-400">{t.order.destCity}</span>
                              <span className="font-medium text-gray-900">{order.destination_city}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-gray-400">{t.order.customsCity}</span>
                              <span className="font-medium text-gray-900">{order.customs_city}</span>
                            </div>
                          </div>
                        </div>

                        {/* 时间信息 */}
                        <div className="bg-white rounded-xl p-4 border border-gray-100 shadow-sm">
                          <h4 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                            <div className="w-6 h-6 bg-purple-100 rounded-lg flex items-center justify-center">
                              <Clock className="w-3.5 h-3.5 text-purple-600" />
                            </div>
                            {t.order.timeInfo}
                          </h4>
                          <div className="space-y-2.5 text-sm">
                            <div className="flex items-center justify-between">
                              <span className="text-gray-400">{t.order.createTime}</span>
                              <span className="text-gray-600">{formatDateTime(order.created_at)}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-gray-400">{t.order.updateTime}</span>
                              <span className="text-gray-600">{formatDateTime(order.updated_at)}</span>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 备注 */}
                      {order.notes && (
                        <div className="mb-6 bg-amber-50/50 rounded-xl p-4 border border-amber-100">
                          <h4 className="text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2">
                            <FileText className="w-4 h-4 text-amber-600" />
                            {t.order.notesInfo}
                          </h4>
                          <p className="text-sm text-gray-600">{order.notes}</p>
                        </div>
                      )}

                      {/* 运输确认按钮 - 仅待确认状态显示 */}
                      {order.status === '待确认' && (
                        <div className="mb-6 bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-4 border border-amber-200">
                          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                            <div className="flex items-center gap-3">
                              <div className="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
                                <ClipboardCheck className="w-5 h-5 text-amber-600" />
                              </div>
                              <div>
                                <h4 className="text-sm font-semibold text-gray-900">{t.order.transportConfirmed}</h4>
                                <p className="text-xs text-gray-500">{t.order.transportConfirmDesc}</p>
                              </div>
                            </div>
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                if (confirm(t.order.confirmDialog)) {
                                  handleConfirmOrder(order.id);
                                }
                              }}
                              disabled={confirmingId === order.id}
                              className="flex items-center gap-2 px-6 py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white text-sm font-medium rounded-xl hover:from-amber-600 hover:to-orange-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md hover:shadow-lg"
                            >
                              {confirmingId === order.id ? (
                                <>
                                  <Loader2 className="w-4 h-4 animate-spin" />
                                  {t.order.confirming}
                                </>
                              ) : (
                                <>
                                  <CheckCircle className="w-4 h-4" />
                                  {t.order.transportConfirm}
                                </>
                              )}
                            </button>
                          </div>
                        </div>
                      )}

                      {/* 聊天区域 */}
                      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
                        <div className="px-4 py-3 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-100">
                          <div className="flex items-center gap-2">
                            <div className="w-6 h-6 bg-blue-100 rounded-lg flex items-center justify-center">
                              <MessageSquare className="w-3.5 h-3.5 text-blue-600" />
                            </div>
                            <h4 className="text-sm font-semibold text-gray-800">{t.order.orderChat}</h4>
                            <span className="text-xs text-gray-400">{t.order.orderChatDesc}</span>
                          </div>
                        </div>
                        <ChatBox orderId={order.id} onMessageSent={fetchUnreadCounts} />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* 底部统计 */}
      {orders.length > 0 && (
        <div className="mt-6 text-center text-sm text-gray-400">
          {locale === 'zh' ? '共' : ''} <span className="font-semibold text-gray-600">{orders.length}</span> {t.order.totalOrders}
        </div>
      )}
    </div>
  );
}
