'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  Package, 
  MapPin, 
  Clock,
  FileText,
  ArrowLeft,
  Loader2,
  Phone,
  Mail,
  User,
  MessageSquare,
  Truck,
  CheckCircle,
  AlertCircle,
  Hourglass,
  Send,
  Sparkles,
  ClipboardCheck,
  PenTool,
  ExternalLink
} from 'lucide-react';
import { useUser } from '@/contexts/user-context';
import { useLanguage } from '@/i18n/LanguageContext';
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;
}

// 状态配置
const statusConfig: Record<string, { 
  bg: string; 
  text: string; 
  gradient: string;
  icon: typeof Package;
  dotColor: string;
  statusKey: string;
}> = {
  '新询价': { 
    bg: 'bg-blue-50', 
    text: 'text-blue-700', 
    gradient: 'from-blue-500 to-blue-600',
    icon: Send,
    dotColor: 'bg-blue-500',
    statusKey: 'newInquiry'
  },
  '待确认': { 
    bg: 'bg-amber-50', 
    text: 'text-amber-700', 
    gradient: 'from-amber-500 to-orange-500',
    icon: Hourglass,
    dotColor: 'bg-amber-500',
    statusKey: 'pendingConfirm'
  },
  '装车方案设计中': { 
    bg: 'bg-cyan-50', 
    text: 'text-cyan-700', 
    gradient: 'from-cyan-500 to-teal-500',
    icon: PenTool,
    dotColor: 'bg-cyan-500',
    statusKey: 'loadingPlan'
  },
  '确认': { 
    bg: 'bg-green-50', 
    text: 'text-green-700', 
    gradient: 'from-green-500 to-emerald-500',
    icon: CheckCircle,
    dotColor: 'bg-green-500',
    statusKey: 'confirmed'
  },
  '运输中（中国境内）': { 
    bg: 'bg-indigo-50', 
    text: 'text-indigo-700', 
    gradient: 'from-indigo-500 to-blue-500',
    icon: Truck,
    dotColor: 'bg-indigo-500',
    statusKey: 'inTransitCN'
  },
  '满洲里仓储中': { 
    bg: 'bg-violet-50', 
    text: 'text-violet-700', 
    gradient: 'from-violet-500 to-purple-500',
    icon: Package,
    dotColor: 'bg-violet-500',
    statusKey: 'manzhouliStorage'
  },
  '清关未完成': { 
    bg: 'bg-orange-50', 
    text: 'text-orange-700', 
    gradient: 'from-orange-500 to-red-500',
    icon: AlertCircle,
    dotColor: 'bg-orange-500',
    statusKey: 'customsUnfinished'
  },
  '运输中（俄罗斯境内）': { 
    bg: 'bg-purple-50', 
    text: 'text-purple-700', 
    gradient: 'from-purple-500 to-violet-500',
    icon: Truck,
    dotColor: 'bg-purple-500',
    statusKey: 'inTransitRU'
  },
  '配送完成': { 
    bg: 'bg-emerald-50', 
    text: 'text-emerald-700', 
    gradient: 'from-emerald-500 to-teal-500',
    icon: Sparkles,
    dotColor: 'bg-emerald-500',
    statusKey: 'delivered'
  },
};

export default function OrderDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { isLoading: userLoading } = useUser();
  const { t, locale } = useLanguage();
  const [order, setOrder] = useState<Order | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [confirming, setConfirming] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const orderNumber = params.orderNumber as string;

  // 获取状态显示文本
  const getStatusText = (status: string): string => {
    const config = statusConfig[status];
    if (config) {
      const statusKey = config.statusKey as keyof typeof t.orderStatus;
      return t.orderStatus[statusKey] || status;
    }
    return status;
  };

  useEffect(() => {
    if (userLoading) return;
    
    const fetchOrder = async () => {
      try {
        const response = await fetch(`/api/orders/by-number/${orderNumber}`);
        const data = await response.json();
        
        if (response.ok) {
          setOrder(data.order);
        } else {
          setError(data.error || t.order.orderNotFound);
        }
      } catch (err) {
        console.error('Error:', err);
        setError(t.order.loadFailed);
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrder();
  }, [orderNumber, userLoading, t]);

  // 确认订单
  const handleConfirmOrder = async () => {
    if (!order) return;
    
    setConfirming(true);
    try {
      const response = await fetch(`/api/orders/${order.id}/confirm`, {
        method: 'POST',
      });
      const data = await response.json();
      
      if (response.ok && data.success) {
        setOrder({ ...order, status: '确认', updated_at: new Date().toISOString() });
      } else {
        alert(data.error || t.order.confirmFailed);
      }
    } catch (error) {
      console.error('Error confirming order:', error);
      alert(t.order.confirmFailed);
    } finally {
      setConfirming(false);
    }
  };

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

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

  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>
    );
  }

  if (error || !order) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="bg-gradient-to-br from-red-50 to-orange-50 rounded-2xl p-12 border border-red-200 text-center">
          <div className="w-20 h-20 bg-gradient-to-br from-red-100 to-orange-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <AlertCircle className="w-10 h-10 text-red-400" />
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">{error || t.order.orderNotFound}</h3>
          <p className="text-gray-500 mb-6">{t.order.checkOrderNumber}</p>
          <Link
            href="/user/orders"
            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"
          >
            <ArrowLeft className="w-4 h-4" />
            {t.order.backToList}
          </Link>
        </div>
      </div>
    );
  }

  const config = statusConfig[order.status] || statusConfig['新询价'];
  const StatusIcon = config.icon;

  return (
    <div className="max-w-4xl mx-auto">
      {/* 返回按钮和标题 */}
      <div className="flex items-center gap-4 mb-6">
        <Link
          href="/user/orders"
          className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-xl text-gray-600 hover:bg-gray-50 hover:border-gray-300 transition-all"
        >
          <ArrowLeft className="w-4 h-4" />
          {t.order.backToList}
        </Link>
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-gray-900">{t.order.orderDetail}</h1>
        </div>
      </div>

      {/* 订单状态卡片 */}
      <div className={`bg-gradient-to-br ${config.bg} rounded-2xl border border-white/50 p-6 mb-6`}>
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="flex items-center gap-4">
            <div className={`w-14 h-14 rounded-2xl bg-gradient-to-br ${config.gradient} flex items-center justify-center shadow-lg`}>
              <StatusIcon className="w-7 h-7 text-white" />
            </div>
            <div>
              <div className="text-sm text-gray-500 mb-1">{t.order.orderNumber}</div>
              <div className="text-2xl font-bold text-gray-900">{order.order_number}</div>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <div className={`w-3 h-3 rounded-full ${config.dotColor} animate-pulse`}></div>
            <span className={`inline-flex items-center px-4 py-2 rounded-xl text-sm font-semibold ${config.bg} ${config.text} border border-white/50`}>
              {getStatusText(order.status)}
            </span>
          </div>
        </div>
      </div>

      {/* 运输路线 */}
      <div className="bg-white rounded-2xl border border-gray-100 p-6 mb-6 shadow-sm">
        <div className="flex items-center gap-2 mb-4">
          <MapPin className="w-5 h-5 text-blue-600" />
          <h3 className="font-semibold text-gray-900">{t.order.route}</h3>
        </div>
        <div className="flex items-center justify-between bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-6">
          <div className="text-center">
            <div className="text-xs text-gray-400 mb-1">{t.order.origin}</div>
            <div className="text-xl font-bold text-gray-900">{order.origin_city}</div>
            <div className="text-xs text-gray-400 mt-1">{t.order.china}</div>
          </div>
          <div className="flex-1 flex items-center justify-center px-6">
            <div className="flex items-center gap-2">
              <div className="w-8 h-0.5 bg-blue-300"></div>
              <Truck className="w-6 h-6 text-blue-500" />
              <div className="w-8 h-0.5 bg-blue-300"></div>
            </div>
          </div>
          <div className="text-center">
            <div className="text-xs text-gray-400 mb-1">{t.order.destination}</div>
            <div className="text-xl font-bold text-gray-900">{order.destination_city}</div>
            <div className="text-xs text-gray-400 mt-1">{t.order.russia}</div>
          </div>
        </div>
        <div className="mt-4 flex items-center gap-2 text-sm text-gray-600">
          <span className="text-gray-400">{t.order.customsCity}:</span>
          <span className="font-medium">{order.customs_city}</span>
        </div>
      </div>

      {/* 信息网格 */}
      <div className="grid md:grid-cols-2 gap-6 mb-6">
        {/* 联系人信息 */}
        <div className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
          <h4 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
              <User className="w-4 h-4 text-blue-600" />
            </div>
            {t.order.contactInfo}
          </h4>
          <div className="space-y-3">
            <div className="flex items-center gap-3 text-gray-600">
              <User className="w-4 h-4 text-gray-300" />
              <span>{order.contact_name}</span>
            </div>
            <div className="flex items-center gap-3 text-gray-600">
              <Phone className="w-4 h-4 text-gray-300" />
              <span>{order.contact_phone}</span>
            </div>
            {order.contact_email && (
              <div className="flex items-center gap-3 text-gray-600">
                <Mail className="w-4 h-4 text-gray-300" />
                <span>{order.contact_email}</span>
              </div>
            )}
          </div>
        </div>

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

      {/* 备注 */}
      {order.notes && (
        <div className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-2xl p-6 border border-amber-200 mb-6">
          <h4 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <FileText className="w-5 h-5 text-amber-600" />
            {t.order.notes}
          </h4>
          <p className="text-gray-600">{order.notes}</p>
        </div>
      )}

      {/* 运输确认 - 仅待确认状态显示 */}
      {order.status === '待确认' && (
        <div className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-2xl p-6 border border-amber-300 mb-6">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-amber-100 rounded-xl flex items-center justify-center">
                <ClipboardCheck className="w-6 h-6 text-amber-600" />
              </div>
              <div>
                <h4 className="font-semibold text-gray-900">{t.order.planSent}</h4>
                <p className="text-sm text-gray-500">{t.order.planSentDesc}</p>
              </div>
            </div>
            <button
              onClick={() => {
                if (confirm(t.order.confirmPlanMsg)) {
                  handleConfirmOrder();
                }
              }}
              disabled={confirming}
              className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-orange-500 text-white 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"
            >
              {confirming ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  {t.order.confirming}
                </>
              ) : (
                <>
                  <CheckCircle className="w-5 h-5" />
                  {t.order.confirmTransport}
                </>
              )}
            </button>
          </div>
        </div>
      )}

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