'use client';

import { useState, useEffect, useRef } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { 
  Package, 
  MapPin, 
  Clock,
  FileText,
  ArrowRight,
  Loader2,
  Search,
  Filter,
  ChevronDown,
  ChevronUp,
  Phone,
  Mail,
  User,
  MessageSquare,
  Truck,
  CheckCircle,
  AlertCircle,
  Hourglass,
  Send,
  Sparkles,
  PenTool,
  Image as ImageIcon,
  Paperclip,
  ExternalLink,
  Bell,
  BellRing
} 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;
}

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

// 状态配置
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-purple-50', 
    text: 'text-purple-700', 
    gradient: 'from-purple-500 to-violet-500',
    icon: Truck,
  },
  '清关未完成': { 
    bg: 'bg-orange-50', 
    text: 'text-orange-700', 
    gradient: 'from-orange-500 to-red-500',
    icon: AlertCircle,
  },
  '配送完成': { 
    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 AdminOrdersPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [orders, setOrders] = useState<Order[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || 'all');
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [sendingMessage, setSendingMessage] = useState(false);
  const [updatingStatus, setUpdatingStatus] = useState<string | null>(null);
  const [totalOrders, setTotalOrders] = useState(0);
  const [unreadCounts, setUnreadCounts] = useState<Record<string, number>>({});
  const [totalUnread, setTotalUnread] = useState(0);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 获取订单列表
  const fetchOrders = async () => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams();
      if (statusFilter && statusFilter !== 'all') {
        params.set('status', statusFilter);
      }
      if (search) {
        params.set('search', search);
      }
      
      const response = await fetch(`/api/admin/orders?${params}`);
      const data = await response.json();
      if (response.ok) {
        setOrders(data.orders || []);
        setTotalOrders(data.total || 0);
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, [statusFilter]);

  // 获取未读消息数
  useEffect(() => {
    if (orders.length === 0) return;

    const fetchUnreadCounts = async () => {
      try {
        const response = await fetch('/api/admin/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);
      }
    };

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

  // 搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchOrders();
  };

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

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

  // 发送消息
  const handleSendMessage = async (orderId: string) => {
    if (!newMessage.trim()) return;
    
    setSendingMessage(true);
    try {
      const response = await fetch(`/api/admin/orders/${orderId}/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 (orderId: string, newStatus: string) => {
    setUpdatingStatus(orderId);
    try {
      const response = await fetch(`/api/orders/${orderId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        setOrders(prev => prev.map(order => 
          order.id === orderId 
            ? { ...order, status: newStatus, updated_at: new Date().toISOString() }
            : order
        ));
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setUpdatingStatus(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',
    });
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-gray-900">订单管理</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} 条新消息
              </span>
            )}
          </div>
          <p className="text-gray-500 mt-1">共 {totalOrders} 个订单</p>
        </div>
      </div>

      {/* 筛选栏 */}
      <div className="bg-white rounded-2xl p-4 border border-gray-100 shadow-sm">
        <div className="flex flex-col sm:flex-row gap-4">
          {/* 搜索 */}
          <form onSubmit={handleSearch} className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="搜索联系人、手机号、城市..."
                className="w-full pl-10 pr-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </form>
          
          {/* 状态筛选 */}
          <div className="flex items-center gap-2">
            <Filter className="w-5 h-5 text-gray-400" />
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部状态</option>
              {statusList.map(status => (
                <option key={status} value={status}>{status}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* 订单列表 */}
      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
        </div>
      ) : orders.length === 0 ? (
        <div className="bg-white rounded-2xl p-12 border border-gray-100 text-center">
          <Package className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <p className="text-gray-500">暂无订单</p>
        </div>
      ) : (
        <div className="space-y-4">
          {orders.map((order) => {
            const config = statusConfig[order.status] || statusConfig['新询价'];
            const StatusIcon = config.icon;
            const isExpanded = expandedId === order.id;
            
            return (
              <div 
                key={order.id} 
                className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm hover:shadow-md transition-shadow"
              >
                {/* 订单头部 */}
                <div className="flex flex-col lg:flex-row lg:items-center gap-4 p-5">
                  {/* 左侧信息 */}
                  <div className="flex-1 flex flex-col sm:flex-row sm: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`}>
                        <StatusIcon className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <div className="text-xs text-gray-400">订单号</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-4 px-4 py-2 bg-gray-50 rounded-xl">
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-gray-400" />
                        <span className="text-sm font-medium text-gray-900">{order.contact_name}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Phone className="w-4 h-4 text-gray-400" />
                        <span className="text-sm text-gray-600">{order.contact_phone}</span>
                      </div>
                    </div>

                    {/* 路线 */}
                    <div className="flex items-center gap-2 text-sm">
                      <span className="font-medium text-gray-900">{order.origin_city}</span>
                      <ArrowRight className="w-4 h-4 text-blue-400" />
                      <span className="font-medium text-gray-900">{order.destination_city}</span>
                    </div>
                  </div>

                  {/* 右侧：状态和操作 */}
                  <div className="flex items-center gap-3">
                    {/* 状态更新 */}
                    <select
                      value={order.status}
                      onChange={(e) => handleUpdateStatus(order.id, e.target.value)}
                      disabled={updatingStatus === order.id}
                      className={`px-3 py-2 rounded-lg text-sm font-medium ${config.bg} ${config.text} border-0 cursor-pointer disabled:opacity-50`}
                    >
                      {statusList.map(status => (
                        <option key={status} value={status}>{status}</option>
                      ))}
                    </select>
                    
                    {/* 日期 */}
                    <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
                      onClick={() => window.open(`/admin/orders/${order.order_number}`, '_blank')}
                      className="flex items-center gap-1 px-3 py-2 text-sm font-medium rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
                    >
                      详情
                      <ExternalLink className="w-3.5 h-3.5" />
                    </button>
                    
                    {/* 展开/收起 */}
                    <button
                      onClick={() => setExpandedId(isExpanded ? null : order.id)}
                      className={`flex items-center gap-1 px-3 py-2 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'
                      }`}
                    >
                      {isExpanded ? '收起' : '展开'}
                      {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                    </button>
                  </div>
                </div>

                {/* 展开的详情 */}
                {isExpanded && (
                  <div className="border-t border-gray-100 bg-gray-50/50">
                    <div className="p-5">
                      {/* 订单信息 */}
                      <div className="grid md:grid-cols-3 gap-4 mb-6">
                        <div className="bg-white rounded-xl p-4 border border-gray-100">
                          <h4 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                            <User className="w-4 h-4 text-blue-600" />
                            联系人
                          </h4>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-gray-400">姓名</span>
                              <span className="text-gray-900">{order.contact_name}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-400">电话</span>
                              <span className="text-gray-900">{order.contact_phone}</span>
                            </div>
                            {order.contact_email && (
                              <div className="flex justify-between">
                                <span className="text-gray-400">邮箱</span>
                                <span className="text-gray-900">{order.contact_email}</span>
                              </div>
                            )}
                          </div>
                        </div>

                        <div className="bg-white rounded-xl p-4 border border-gray-100">
                          <h4 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                            <MapPin className="w-4 h-4 text-green-600" />
                            运输路线
                          </h4>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-gray-400">起运地</span>
                              <span className="text-gray-900">{order.origin_city}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-400">目的地</span>
                              <span className="text-gray-900">{order.destination_city}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-400">清关地</span>
                              <span className="text-gray-900">{order.customs_city}</span>
                            </div>
                          </div>
                        </div>

                        <div className="bg-white rounded-xl p-4 border border-gray-100">
                          <h4 className="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                            <Clock className="w-4 h-4 text-purple-600" />
                            时间
                          </h4>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-gray-400">创建</span>
                              <span className="text-gray-900">{formatDateTime(order.created_at)}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-400">更新</span>
                              <span className="text-gray-900">{formatDateTime(order.updated_at)}</span>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 备注 */}
                      {order.notes && (
                        <div className="mb-6 bg-amber-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" />
                            备注
                          </h4>
                          <p className="text-sm text-gray-600">{order.notes}</p>
                        </div>
                      )}

                      {/* 消息区域 */}
                      <div className="bg-white rounded-xl border border-gray-100 overflow-hidden">
                        <div className="px-4 py-3 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-100">
                          <h4 className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                            <MessageSquare className="w-4 h-4 text-blue-600" />
                            订单沟通
                          </h4>
                        </div>
                        
                        {/* 消息列表 */}
                        <div className="h-64 overflow-y-auto p-4 space-y-3">
                          {messages.length === 0 ? (
                            <div className="text-center text-gray-400 text-sm py-8">
                              暂无消息记录
                            </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' 
                                    ? 'bg-blue-600 text-white rounded-2xl rounded-br-md' 
                                    : 'bg-gray-100 text-gray-900 rounded-2xl rounded-bl-md'
                                } px-4 py-2`}>
                                  <div className="text-xs opacity-70 mb-1">
                                    {msg.sender_name || (msg.sender_type === 'admin' ? '客服' : '客户')}
                                  </div>
                                  {msg.message_type === 'text' ? (
                                    <p className="text-sm">{msg.content}</p>
                                  ) : msg.message_type === 'image' ? (
                                    <img src={msg.file_url || ''} alt="图片" className="max-w-full rounded" />
                                  ) : (
                                    <a 
                                      href={msg.file_url || ''} 
                                      target="_blank" 
                                      rel="noopener noreferrer"
                                      className="flex items-center gap-2 text-sm underline"
                                    >
                                      <Paperclip className="w-4 h-4" />
                                      {msg.file_name || '文件'}
                                    </a>
                                  )}
                                  <div className={`text-xs mt-1 opacity-50`}>
                                    {formatDateTime(msg.created_at)}
                                  </div>
                                </div>
                              </div>
                            ))
                          )}
                          <div ref={messagesEndRef} />
                        </div>
                        
                        {/* 发送消息 */}
                        <div className="px-4 py-3 border-t border-gray-100">
                          <div className="flex gap-2">
                            <input
                              type="text"
                              value={newMessage}
                              onChange={(e) => setNewMessage(e.target.value)}
                              onKeyDown={(e) => {
                                if (e.key === 'Enter' && !e.shiftKey) {
                                  e.preventDefault();
                                  handleSendMessage(order.id);
                                }
                              }}
                              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(order.id)}
                              disabled={sendingMessage || !newMessage.trim()}
                              className="flex items-center justify-center w-10 h-10 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                            >
                              {sendingMessage ? (
                                <Loader2 className="w-5 h-5 animate-spin" />
                              ) : (
                                <Send className="w-5 h-5" />
                              )}
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
