'use client';

import { useState, useEffect, useRef } 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,
  PenTool,
  Image as ImageIcon,
  Paperclip
} from 'lucide-react';
import { ORDER_STATUS } from '@/storage/database/shared/schema';

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 Message {
  id: string;
  order_id: string;
  sender_type: string;
  sender_id: string;
  sender_name: string | null;
  message_type: string;
  content: string | null;
  file_url: string | null;
  file_name: string | null;
  file_size: string | null;
  created_at: string;
}

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

const statusList = Object.values(ORDER_STATUS);

export default function AdminOrderDetailPage() {
  const params = useParams();
  const router = useRouter();
  const [order, setOrder] = useState<Order | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [sendingMessage, setSendingMessage] = useState(false);
  const [updatingStatus, setUpdatingStatus] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const orderNumber = params.orderNumber as string;

  // 获取订单详情
  useEffect(() => {
    const fetchOrder = async () => {
      try {
        const response = await fetch(`/api/admin/orders/by-number/${orderNumber}`);
        const data = await response.json();
        
        if (response.ok) {
          setOrder(data.order);
        } else {
          setError(data.error || '订单不存在');
        }
      } catch (err) {
        console.error('Error:', err);
        setError('加载订单失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrder();
  }, [orderNumber]);

  // 获取消息
  useEffect(() => {
    if (!order) return;
    
    const fetchMessages = async () => {
      try {
        const response = await fetch(`/api/admin/orders/${order.id}/messages`);
        const data = await response.json();
        if (response.ok) {
          setMessages(data.messages || []);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    };
    
    fetchMessages();
  }, [order]);

  // 滚动到消息底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 发送消息
  const handleSendMessage = async () => {
    if (!order || !newMessage.trim()) return;
    
    setSendingMessage(true);
    try {
      const response = await fetch(`/api/admin/orders/${order.id}/messages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: newMessage, messageType: 'text' }),
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        setMessages(prev => [...prev, data.message]);
        setNewMessage('');
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setSendingMessage(false);
    }
  };

  // 更新订单状态
  const handleUpdateStatus = async (newStatus: string) => {
    if (!order) return;
    
    setUpdatingStatus(true);
    try {
      const response = await fetch(`/api/orders/${order.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        setOrder({ ...order, status: newStatus, updated_at: new Date().toISOString() });
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setUpdatingStatus(false);
    }
  };

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

  if (isLoading) {
    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="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 || '订单不存在'}</h3>
        <p className="text-gray-500 mb-6">请检查订单号是否正确</p>
        <Link
          href="/admin/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" />
          返回订单列表
        </Link>
      </div>
    );
  }

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

  return (
    <div className="space-y-6">
      {/* 返回按钮和标题 */}
      <div className="flex items-center gap-4">
        <Link
          href="/admin/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" />
          返回列表
        </Link>
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-gray-900">订单详情</h1>
        </div>
      </div>

      {/* 订单状态卡片 */}
      <div className={`bg-gradient-to-br ${config.bg} rounded-2xl border border-white/50 p-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">订单号</div>
              <div className="text-2xl font-bold text-gray-900">{order.order_number}</div>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <span className={`inline-flex items-center px-4 py-2 rounded-xl text-sm font-semibold ${config.bg} ${config.text} border border-white/50`}>
              {order.status}
            </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">更新订单状态</h4>
        <div className="flex flex-wrap gap-2">
          {statusList.map(status => {
            const sConfig = statusConfig[status];
            const isActive = order.status === status;
            return (
              <button
                key={status}
                onClick={() => handleUpdateStatus(status)}
                disabled={updatingStatus || isActive}
                className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition-all ${
                  isActive 
                    ? `${sConfig.bg} ${sConfig.text} border-2 border-current` 
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                } disabled:opacity-50`}
              >
                <sConfig.icon className="w-4 h-4" />
                {status}
              </button>
            );
          })}
        </div>
      </div>

      {/* 运输路线 */}
      <div className="bg-white rounded-2xl border border-gray-100 p-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">运输路线</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">起运地</div>
            <div className="text-xl font-bold text-gray-900">{order.origin_city}</div>
            <div className="text-xs text-gray-400 mt-1">中国</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">目的地</div>
            <div className="text-xl font-bold text-gray-900">{order.destination_city}</div>
            <div className="text-xs text-gray-400 mt-1">俄罗斯</div>
          </div>
        </div>
        <div className="mt-4 flex items-center gap-2 text-sm text-gray-600">
          <span className="text-gray-400">清关地点:</span>
          <span className="font-medium">{order.customs_city}</span>
        </div>
      </div>

      {/* 信息网格 */}
      <div className="grid md:grid-cols-2 gap-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>
            联系人信息
          </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>
            时间信息
          </h4>
          <div className="space-y-3">
            <div className="flex items-center justify-between text-gray-600">
              <span className="text-gray-400">创建时间</span>
              <span>{formatDateTime(order.created_at)}</span>
            </div>
            <div className="flex items-center justify-between text-gray-600">
              <span className="text-gray-400">更新时间</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">
          <h4 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <FileText className="w-5 h-5 text-amber-600" />
            备注信息
          </h4>
          <p className="text-gray-600">{order.notes}</p>
        </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">订单沟通</h4>
              <p className="text-xs text-gray-400">{messages.length} 条消息</p>
            </div>
          </div>
        </div>
        
        {/* 消息列表 */}
        <div className="h-80 overflow-y-auto p-4 space-y-3 bg-gray-50">
          {messages.length === 0 ? (
            <div className="text-center py-8 text-gray-400">
              <MessageSquare className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p className="text-sm">暂无消息</p>
            </div>
          ) : (
            messages.map((msg) => (
              <div
                key={msg.id}
                className={`flex ${msg.sender_type === 'admin' ? 'justify-end' : 'justify-start'}`}
              >
                <div className={`max-w-[70%] ${msg.sender_type === 'admin' ? 'order-2' : 'order-1'}`}>
                  <div className="flex items-center gap-2 mb-1">
                    {msg.sender_type === 'admin' ? (
                      <span className="text-xs text-blue-600 font-medium">客服</span>
                    ) : (
                      <span className="text-xs text-gray-500">{msg.sender_name || '客户'}</span>
                    )}
                    <span className="text-xs text-gray-400">{formatDateTime(msg.created_at)}</span>
                  </div>
                  {msg.message_type === 'text' ? (
                    <div className={`px-4 py-2 rounded-2xl whitespace-pre-wrap ${
                      msg.sender_type === 'admin' 
                        ? 'bg-blue-500 text-white rounded-br-md' 
                        : 'bg-white text-gray-700 rounded-bl-md border border-gray-100'
                    }`}>
                      {msg.content}
                    </div>
                  ) : msg.message_type === 'image' ? (
                    <div className="bg-white rounded-2xl p-2 border border-gray-100">
                      <img src={msg.file_url || ''} alt="图片" className="max-w-full rounded-lg" />
                    </div>
                  ) : (
                    <a
                      href={msg.file_url || '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-2 px-4 py-2 bg-white rounded-2xl border border-gray-100 hover:bg-gray-50"
                    >
                      <Paperclip className="w-4 h-4 text-gray-400" />
                      <span className="text-sm text-gray-600">{msg.file_name || '下载文件'}</span>
                    </a>
                  )}
                </div>
              </div>
            ))
          )}
          <div ref={messagesEndRef} />
        </div>
        
        {/* 发送消息 */}
        <div className="p-4 border-t border-gray-100 bg-white">
          <div className="flex gap-3">
            <input
              type="text"
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleSendMessage()}
              placeholder="输入消息..."
              className="flex-1 px-4 py-2 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <button
              onClick={handleSendMessage}
              disabled={sendingMessage || !newMessage.trim()}
              className="px-4 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 transition-colors"
            >
              {sendingMessage ? <Loader2 className="w-5 h-5 animate-spin" /> : <Send className="w-5 h-5" />}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
