'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { ShoppingBag, Search, CheckCircle, Clock, XCircle, AlertCircle, Download, Eye, MessageCircle, Star } from 'lucide-react';
import Link from 'next/link';
import ProductImageWithFallback from '@/components/ProductImageWithFallback';

interface Order {
  id: string;
  totalAmount: number;
  status: string;
  createdAt: string;
  deliveredAt?: string | null;
  seller?: { name: string; id: string };
  dispute?: { id: string; status: string } | null;
  items?: { product: { name: string; slug: string; image: string; deliveryMethod?: string }; quantity: number; price: number }[];
}

const STATUS_MAP: Record<string, { label: string; color: string; icon: any }> = {
  PENDING:   { label: 'Chờ xử lý',   color: 'orange', icon: Clock },
  ESCROW:    { label: 'Đang giữ tiền',color: 'yellow', icon: Clock },
  PROCESSING:{ label: 'Đang xử lý',  color: 'blue',   icon: Clock },
  DELIVERED: { label: 'Đã giao - chờ xác nhận', color: 'blue', icon: CheckCircle },
  COMPLETED: { label: 'Hoàn thành',  color: 'teal',   icon: CheckCircle },
  CANCELLED: { label: 'Đã hủy',      color: 'red',    icon: XCircle },
  DISPUTED:  { label: 'Tranh chấp',  color: 'red',    icon: AlertCircle },
};

export default function UserOrdersPage() {
  const user = useAuthStore((state) => state.user);
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [confirmingId, setConfirmingId] = useState<string | null>(null);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [cancelEligibility, setCancelEligibility] = useState<any | null>(null);
  const [cancellingOrderId, setCancellingOrderId] = useState<string | null>(null);
  const [now, setNow] = useState(() => Date.now());
  const [chatOrder, setChatOrder] = useState<Order | null>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [messageText, setMessageText] = useState('');
  const [reviewOrder, setReviewOrder] = useState<Order | null>(null);
  const [rating, setRating] = useState(5);
  const [reviewComment, setReviewComment] = useState('');

  // Dispute modal state
  const [showDisputeModal, setShowDisputeModal] = useState(false);
  const [disputeOrderId, setDisputeOrderId] = useState<string | null>(null);
  const [disputeReason, setDisputeReason] = useState('');
  const [isSubmittingDispute, setIsSubmittingDispute] = useState(false);

  const fetchOrders = () => {
    setLoading(true);
    api.get('/orders/buyer')
      .then(res => setOrders(res.data?.data || res.data || []))
      .catch(console.error)
      .finally(() => setLoading(false));
  };

  const openChat = async (order: Order) => { setChatOrder(order); setMessages([]); try { const res = await api.get(`/orders/${order.id}/messages`); setMessages(res.data || []); } catch { alert('Không thể tải cuộc trò chuyện.'); } };
  const sendChat = async () => { if (!chatOrder || !messageText.trim()) return; try { const res = await api.post(`/orders/${chatOrder.id}/messages`, { content: messageText }); setMessages((items) => [...items, res.data]); setMessageText(''); } catch (e: any) { alert(e.response?.data?.message || 'Không thể gửi tin nhắn.'); } };
  const requestAdminInChat = async () => { if (!chatOrder) return; try { await api.post(`/orders/${chatOrder.id}/messages/request-admin`); const res = await api.get(`/orders/${chatOrder.id}/messages`); setMessages(res.data || []); } catch (e: any) { alert(e.response?.data?.message || 'Không thể mời admin vào cuộc trò chuyện.'); } };
  const submitReview = async () => { if (!reviewOrder) return; try { await api.post(`/orders/${reviewOrder.id}/review`, { rating, comment: reviewComment }); setReviewOrder(null); setReviewComment(''); alert('Đánh giá đã được gửi.'); fetchOrders(); } catch (e: any) { alert(e.response?.data?.message || 'Không thể gửi đánh giá.'); } };

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

  useEffect(() => {
    if (!chatOrder) return;
    const timer = setInterval(async () => { try { const res = await api.get(`/orders/${chatOrder.id}/messages`); setMessages(res.data || []); } catch { /* preserve the current visible history */ } }, 3000);
    return () => clearInterval(timer);
  }, [chatOrder?.id]);

  useEffect(() => {
    const timer = window.setInterval(() => setNow(Date.now()), 1000);
    return () => window.clearInterval(timer);
  }, []);

  useEffect(() => {
    if (!selectedOrder) { setCancelEligibility(null); return; }
    let active = true;
    const loadEligibility = async () => {
      try {
        const response = await api.get(`/orders/${selectedOrder.id}/cancel-eligibility`);
        if (active) setCancelEligibility(response.data);
      } catch { if (active) setCancelEligibility(null); }
    };
    void loadEligibility();
    const poll = window.setInterval(loadEligibility, 15000);
    return () => { active = false; window.clearInterval(poll); };
  }, [selectedOrder?.id]);

  const handleConfirmOrder = async (orderId: string) => {
    if (!confirm('Bạn xác nhận đã nhận được hàng? Đơn sẽ hoàn thành và tiền được giải ngân; bạn vẫn có thể khiếu nại trong thời hạn bảo hành.')) return;
    setConfirmingId(orderId);
    try {
      await api.post(`/orders/${orderId}/confirm`);
      fetchOrders();
    } catch (error: any) {
      alert(error.response?.data?.message || 'Có lỗi xảy ra khi xác nhận đơn hàng');
    } finally {
      setConfirmingId(null);
    }
  };

  const handleManualNoResponseCancel = async (order: Order) => {
    if (!confirm('Hủy đơn thủ công và hoàn toàn bộ tiền về ví của bạn? Chỉ thực hiện khi người bán chưa phản hồi.')) return;
    try {
      setCancellingOrderId(order.id);
      await api.post(`/orders/${order.id}/cancel-unresponsive`);
      setSelectedOrder(null);
      fetchOrders();
      alert('Đơn hàng đã được hủy. Tiền đã hoàn về ví của bạn.');
    } catch (error: any) {
      alert(error.response?.data?.message || 'Đơn chưa đủ điều kiện để hoàn tiền tự động.');
      try { const response = await api.get(`/orders/${order.id}/cancel-eligibility`); setCancelEligibility(response.data); } catch { /* keep the existing message */ }
    } finally { setCancellingOrderId(null); }
  };

  const downloadOrder = async (orderId: string, isTxt = false) => {
    try {
      const response = await api.get(`/orders/${orderId}/download`, { responseType: 'blob' });
      const url = URL.createObjectURL(response.data);
      const link = document.createElement('a'); link.href = url; link.download = `order-${orderId}.${isTxt ? 'txt' : 'zip'}`; link.click(); URL.revokeObjectURL(url);
    } catch (error: any) { alert(error.response?.data?.message || 'Không thể tải sản phẩm.'); }
  };

  const handleCreateDispute = async () => {
    if (!disputeOrderId || !disputeReason.trim()) return;
    setIsSubmittingDispute(true);
    try {
      await api.post('/disputes/create', {
        orderId: disputeOrderId,
        reason: disputeReason
      });
      setShowDisputeModal(false);
      setDisputeReason('');
      setDisputeOrderId(null);
      fetchOrders();
      alert('Đã tạo khiếu nại thành công!');
    } catch (error: any) {
      alert(error.response?.data?.message || 'Có lỗi xảy ra khi tạo khiếu nại');
    } finally {
      setIsSubmittingDispute(false);
    }
  };

  const filtered = orders.filter(o => {
    const matchSearch =
      o.id.toLowerCase().includes(search.toLowerCase()) ||
      (o.seller?.name || '').toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === 'ALL' || o.status === statusFilter;
    return matchSearch && matchStatus;
  });

  const statusCounts = orders.reduce((acc: Record<string, number>, o) => {
    acc[o.status] = (acc[o.status] || 0) + 1;
    return acc;
  }, {});

  const cancelRemainingSeconds = cancelEligibility?.eligibleAt
    ? Math.max(0, Math.ceil((new Date(cancelEligibility.eligibleAt).getTime() - now) / 1000))
    : 0;
  const cancelCountdown = `${String(Math.floor(cancelRemainingSeconds / 60)).padStart(2, '0')}:${String(cancelRemainingSeconds % 60).padStart(2, '0')}`;
  const canUseNoResponseCancellation = Boolean(
    selectedOrder && cancelEligibility?.isManual && selectedOrder.status === 'ESCROW'
    && !cancelEligibility?.sellerResponded && cancelRemainingSeconds === 0
  );

  return (
    <div className="max-w-6xl mx-auto px-4 py-8 space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-black text-white uppercase tracking-tight">Đơn hàng của tôi</h2>
        <p className="text-gray-500 text-sm mt-1">Quản lý và xác nhận các đơn hàng bạn đã mua trên SHOP MMO.</p>
      </div>

      {/* Status Filter Tabs */}
      <div className="flex gap-2 flex-wrap">
        {[
          { key: 'ALL', label: 'Tất cả', count: orders.length },
          ...Object.entries(STATUS_MAP).map(([key, val]) => ({
            key,
            label: val.label,
            count: statusCounts[key] || 0,
          }))
        ].map(tab => (
          <button
            key={tab.key}
            onClick={() => setStatusFilter(tab.key)}
            className={`flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold transition-all ${
              statusFilter === tab.key
                ? 'bg-red-500/10 border border-red-500/30 text-red-500'
                : 'bg-[#141414] border border-white/5 text-gray-400 hover:text-white'
            }`}
          >
            {tab.label}
            <span className={`px-1.5 py-0.5 rounded-md text-[10px] ${
              statusFilter === tab.key ? 'bg-red-500/20' : 'bg-white/5'
            }`}>{tab.count}</span>
          </button>
        ))}
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
        <input
          type="text"
          placeholder="Tìm đơn hàng theo ID hoặc tên gian hàng..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full bg-[#141414] border border-white/10 rounded-xl pl-10 pr-4 py-3 text-white placeholder-gray-500 text-sm focus:outline-none focus:border-red-500/50"
        />
      </div>

      {/* Orders Table */}
      <div className="bg-[#141414] border border-white/5 rounded-2xl overflow-hidden shadow-2xl">
        <div className="grid grid-cols-12 gap-4 px-6 py-4 border-b border-white/5 text-xs text-gray-500 font-bold uppercase tracking-wider">
          <div className="col-span-3">Mã đơn & Sản phẩm</div>
          <div className="col-span-2">Gian hàng</div>
          <div className="col-span-2">Ngày đặt</div>
          <div className="col-span-2 text-right">Tổng tiền</div>
          <div className="col-span-3 text-center">Trạng thái & Hành động</div>
        </div>

        {loading ? (
          <div>
            {[1,2,3].map(i => (
              <div key={i} className="grid grid-cols-12 gap-4 px-6 py-5 border-b border-white/5">
                {[3,2,2,2,3].map((span, j) => (
                  <div key={j} className={`col-span-${span} h-5 bg-white/5 rounded animate-pulse`} />
                ))}
              </div>
            ))}
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-gray-500">
            <ShoppingBag className="w-16 h-16 mb-4 opacity-20" />
            <p className="text-sm font-medium">
              {search || statusFilter !== 'ALL' ? 'Không tìm thấy đơn hàng phù hợp' : 'Bạn chưa mua đơn hàng nào'}
            </p>
          </div>
        ) : (
          filtered.map((order) => {
            const statusInfo = STATUS_MAP[order.status] || { label: order.status, color: 'gray', icon: Clock };
            const Icon = statusInfo.icon;
            return (
              <div
                key={order.id}
                className="grid grid-cols-12 gap-4 px-6 py-5 border-b border-white/5 last:border-0 hover:bg-white/2 transition-colors items-center"
              >
                {/* Cột 1: Thông tin đơn và sản phẩm */}
                <div className="col-span-3">
                  <p className="text-white text-sm font-mono font-bold mb-1.5 flex items-center gap-2">
                    #{order.id.slice(0, 8).toUpperCase()}
                  </p>
                  <div className="space-y-1">
                    {order.items?.map((item, idx) => (
                      <div key={idx} className="flex items-center gap-2">
                        {item.product?.image ? (
                          <ProductImageWithFallback src={item.product.image} alt={item.product.name} className="w-6 h-6 rounded bg-white/10 object-cover" />
                        ) : (
                          <div className="w-6 h-6 rounded bg-white/5" />
                        )}
                        <Link href={`/vi/product/${item.product?.slug}`} className="text-gray-400 text-xs hover:text-red-400 truncate max-w-[150px]">
                          {item.product?.name || 'Sản phẩm'} x{item.quantity}
                        </Link>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Cột 2: Gian hàng */}
                <div className="col-span-2">
                  <p className="text-white text-sm font-medium flex items-center gap-2">
                    <span className="w-5 h-5 rounded-full bg-white/10 flex items-center justify-center text-[10px]">
                      {(order.seller?.name || 'S')[0].toUpperCase()}
                    </span>
                    {order.seller?.name || 'Gian hàng ẩn'}
                  </p>
                </div>

                {/* Cột 3: Ngày đặt */}
                <div className="col-span-2">
                  <p className="text-gray-300 text-xs font-medium">
                    {new Date(order.createdAt).toLocaleDateString('vi-VN')}
                  </p>
                  <p className="text-gray-500 text-xs mt-0.5">
                    {new Date(order.createdAt).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })}
                  </p>
                </div>

                {/* Cột 4: Tổng tiền */}
                <div className="col-span-2 text-right">
                  <p className="text-white text-sm font-bold tracking-tight">
                    {Number(order.totalAmount).toLocaleString('vi-VN')} đ
                  </p>
                </div>

                {/* Cột 5: Trạng thái & Action */}
                <div className="col-span-3 flex flex-col items-center gap-2">
                  <span className={`inline-flex items-center gap-1.5 text-[10px] font-bold px-2.5 py-1 rounded-full bg-${statusInfo.color}-500/10 text-${statusInfo.color}-400 border border-${statusInfo.color}-500/20`}>
                    <Icon className="w-3.5 h-3.5" />
                    {statusInfo.label}
                  </span>
                  <button onClick={() => setSelectedOrder(order)} className="flex h-9 w-full max-w-[180px] items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 text-xs font-bold text-gray-100 transition-colors hover:bg-white/10"><Eye className="w-4 h-4" />Xem chi tiết</button>
                </div>
              </div>
            );
          })
        )}
      </div>

      {selectedOrder && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm">
          <div className="w-full max-w-2xl rounded-2xl border border-white/10 bg-[#17191f] p-6 shadow-2xl">
            <div className="flex items-start justify-between gap-4 border-b border-white/10 pb-4"><div><p className="text-xs font-bold text-gray-500">CHI TIẾT ĐƠN HÀNG</p><h3 className="mt-1 text-xl font-black text-white">#{selectedOrder.id.slice(0, 8).toUpperCase()}</h3></div><button onClick={() => setSelectedOrder(null)} className="rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-300">Đóng</button></div>
            <div className="mt-5 grid gap-4 sm:grid-cols-2"><div className="rounded-xl border border-white/10 bg-black/20 p-4"><p className="text-xs font-bold text-gray-500">NGƯỜI BÁN</p><p className="mt-2 font-bold text-white">{selectedOrder.seller?.name || 'Gian hàng ẩn'}</p><p className="mt-3 text-xs text-gray-500">Ngày đặt: {new Date(selectedOrder.createdAt).toLocaleString('vi-VN')}</p></div><div className="rounded-xl border border-white/10 bg-black/20 p-4"><p className="text-xs font-bold text-gray-500">THANH TOÁN</p><p className="mt-2 text-xl font-black text-rose-400">{Number(selectedOrder.totalAmount).toLocaleString('vi-VN')} đ</p><p className="mt-3 text-xs text-gray-400">Trạng thái: {STATUS_MAP[selectedOrder.status]?.label || selectedOrder.status}</p></div></div>
            <div className="mt-4 rounded-xl border border-white/10"><p className="border-b border-white/10 px-4 py-3 text-sm font-bold text-white">Sản phẩm đã mua</p>{selectedOrder.items?.map((item, index) => <div key={index} className="flex items-center justify-between gap-3 px-4 py-3 text-sm"><span className="text-gray-200">{item.product?.name || 'Sản phẩm'} × {item.quantity}{item.product?.deliveryMethod === 'AUTO_TXT' && <small className="mt-1 block font-bold text-cyan-300">Giao tự động TXT · {item.quantity} tài khoản · tải file .txt</small>}{item.product?.deliveryMethod === 'AUTO_ZIP' && <small className="mt-1 block font-bold text-violet-300">Giao tự động ZIP · tải file .zip</small>}</span><b className="text-white">{Number(item.price).toLocaleString('vi-VN')} đ</b></div>)}</div>
            <div className="mt-5 grid gap-2 sm:grid-cols-2">
              <button onClick={() => { setSelectedOrder(null); openChat(selectedOrder); }} className="flex items-center justify-center gap-2 rounded-lg border border-violet-500/40 bg-violet-500/10 px-4 py-2.5 text-sm font-bold text-violet-300"><MessageCircle className="h-4 w-4" />Chat với người bán</button>
              {selectedOrder.status === 'DELIVERED' && <div><button onClick={() => handleConfirmOrder(selectedOrder.id)} disabled={confirmingId === selectedOrder.id} className="flex w-full items-center justify-center gap-2 rounded-lg border border-teal-500/40 bg-teal-500/10 px-4 py-2.5 text-sm font-bold text-teal-300 disabled:opacity-50"><CheckCircle className="h-4 w-4" />{confirmingId === selectedOrder.id ? 'Đang xác nhận...' : 'Xác nhận đã nhận hàng'}</button><p className="mt-1 text-center text-[10px] text-teal-300/70">Nếu không xác nhận, hệ thống sẽ tự xác nhận sau 1 giờ kể từ lúc đơn được giao.</p></div>}
              {selectedOrder.status === 'DELIVERED' && selectedOrder.items?.some((item) => ['AUTO', 'AUTO_ZIP', 'AUTO_TXT'].includes(item.product?.deliveryMethod || '')) && <button onClick={() => downloadOrder(selectedOrder.id, selectedOrder.items?.[0]?.product?.deliveryMethod === 'AUTO_TXT')} className="flex items-center justify-center gap-2 rounded-lg border border-blue-500/40 bg-blue-500/10 px-4 py-2.5 text-sm font-bold text-blue-300"><Download className="h-4 w-4" />Tải sản phẩm đã giao</button>}
              {['DELIVERED', 'COMPLETED'].includes(selectedOrder.status) && <button onClick={() => { setSelectedOrder(null); setReviewOrder(selectedOrder); }} className="flex items-center justify-center gap-2 rounded-lg border border-amber-400/40 bg-amber-400/10 px-4 py-2.5 text-sm font-bold text-amber-300"><Star className="h-4 w-4" />Đánh giá người bán</button>}
              {['ESCROW', 'DELIVERED', 'COMPLETED'].includes(selectedOrder.status) && !selectedOrder.dispute && <button onClick={() => { setSelectedOrder(null); setDisputeOrderId(selectedOrder.id); setShowDisputeModal(true); }} className="flex items-center justify-center gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-4 py-2.5 text-sm font-bold text-red-300"><AlertCircle className="h-4 w-4" />Khiếu nại / mời admin hỗ trợ</button>}
              {selectedOrder.dispute && <Link href="/vi/profile/complaints" className="flex items-center justify-center gap-2 rounded-lg border border-orange-500/40 bg-orange-500/10 px-4 py-2.5 text-sm font-bold text-orange-300"><AlertCircle className="h-4 w-4" />Xem tiến trình khiếu nại</Link>}
            </div>
            {cancelEligibility?.isManual && selectedOrder.status === 'ESCROW' && <div className="mt-3 rounded-xl border border-rose-500/25 bg-rose-500/[.07] p-3"><div className="flex flex-wrap items-center justify-between gap-3"><div><p className="text-sm font-bold text-rose-200">Không mua nữa</p><p className="mt-1 text-xs text-zinc-400">Chỉ áp dụng cho giao thủ công khi người bán chưa phản hồi.</p></div><button onClick={() => handleManualNoResponseCancel(selectedOrder)} disabled={!canUseNoResponseCancellation || cancellingOrderId === selectedOrder.id} className="rounded-lg border border-rose-400/40 bg-rose-500/15 px-4 py-2.5 text-xs font-black text-rose-200 disabled:cursor-not-allowed disabled:opacity-40">{cancellingOrderId === selectedOrder.id ? 'Đang hoàn tiền...' : canUseNoResponseCancellation ? 'Hủy đơn & hoàn tiền' : `Mở sau ${cancelCountdown}`}</button></div><p className="mt-2 text-[11px] text-zinc-500">{cancelEligibility.sellerResponded ? 'Người bán đã phản hồi; bạn có thể tiếp tục chat hoặc khiếu nại.' : cancelRemainingSeconds > 0 ? `Người bán có ${cancelCountdown} để phản hồi trước khi bạn được hủy đơn.` : 'Đã đủ thời gian. Bạn có thể hủy đơn và nhận tiền hoàn về ví.'}</p></div>}
          </div>
        </div>
      )}

      {chatOrder && <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"><div className="flex h-[520px] w-full max-w-xl flex-col rounded-2xl border border-white/10 bg-[#17191f] p-5"><div className="flex items-center justify-between border-b border-white/10 pb-3"><div><b>Chat với {chatOrder.seller?.name || 'người bán'}</b><p className="text-xs text-gray-500">Trao đổi trực tiếp theo đơn hàng.</p></div><button onClick={() => setChatOrder(null)}>Đóng</button></div><div className="flex-1 space-y-3 overflow-y-auto py-4">{messages.length ? messages.map((m) => { const mine = m.senderId === user?.id; const senderName = mine ? (user?.name || 'Bạn') : (m.sender?.name || chatOrder.seller?.name || 'Người bán'); const senderRole = mine ? 'BUYER' : (m.sender?.role?.name || 'SELLER'); return <div key={m.id} className={`flex ${mine ? 'justify-end' : 'justify-start'}`}><div className={`max-w-[82%] rounded-xl border p-3 text-sm ${mine ? 'border-violet-400/30 bg-violet-600 text-white' : 'border-white/5 bg-white/5 text-gray-200'}`}><p className={`mb-1 text-[11px] font-bold ${mine ? 'text-violet-100' : 'text-cyan-300'}`}>{senderName} · {senderRole}</p><p>{m.content}</p>{m.attachment && <button onClick={async () => { const res = await api.get(`/orders/${chatOrder.id}/messages/${m.id}/download`, { responseType: 'blob' }); const url = URL.createObjectURL(res.data); const link = document.createElement('a'); link.href = url; link.download = m.attachment.name; link.click(); URL.revokeObjectURL(url); }} className={`mt-2 inline-flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-bold ${mine ? 'border-white/30 bg-white/10 text-white' : 'border-blue-500/30 bg-blue-500/10 text-blue-300'}`}><Download className="h-4 w-4" />Tải ZIP: {m.attachment.name}</button>}</div></div>; }) : <p className="text-center text-sm text-gray-500">Chưa có tin nhắn. Hãy bắt đầu trao đổi với người bán.</p>}</div><div className="border-t border-white/10 pt-3"><button onClick={requestAdminInChat} className="mb-3 flex w-full items-center justify-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs font-bold text-amber-300"><AlertCircle className="h-4 w-4" />Mời admin vào cuộc trò chuyện</button><div className="flex gap-2"><input value={messageText} onChange={(e) => setMessageText(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && sendChat()} className="flex-1 rounded-lg bg-black/30 px-3 py-2 text-sm" placeholder="Nhập tin nhắn" /><button onClick={sendChat} className="rounded-lg bg-violet-600 px-4 text-sm font-bold">Gửi</button></div></div></div></div>}
      {reviewOrder && <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"><div className="w-full max-w-md rounded-2xl border border-white/10 bg-[#17191f] p-6"><h3 className="text-xl font-bold">Đánh giá người bán</h3><div className="mt-4 flex gap-2">{[1,2,3,4,5].map((n) => <button key={n} onClick={() => setRating(n)} className={n <= rating ? 'text-amber-400' : 'text-gray-600'}><Star className="h-7 w-7 fill-current" /></button>)}</div><textarea value={reviewComment} onChange={(e) => setReviewComment(e.target.value)} className="mt-4 h-28 w-full rounded-lg bg-black/30 p-3 text-sm" placeholder="Chia sẻ trải nghiệm của bạn (không bắt buộc)" /><div className="mt-4 flex justify-end gap-2"><button onClick={() => setReviewOrder(null)}>Hủy</button><button onClick={submitReview} className="rounded-lg bg-amber-500 px-4 py-2 font-bold text-black">Gửi đánh giá</button></div></div></div>}
      {/* Create Dispute Modal */}
      {showDisputeModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
          <div className="bg-[#1a1b1e] border border-white/10 rounded-2xl w-full max-w-md p-6 shadow-2xl">
            <h3 className="text-xl font-bold text-white mb-2 flex items-center gap-2">
              <AlertCircle className="w-6 h-6 text-red-500" />
              Tạo khiếu nại
            </h3>
            <p className="text-gray-400 text-sm mb-6">
              Bạn đang tạo khiếu nại cho đơn hàng <span className="text-white font-mono">{disputeOrderId?.slice(0, 8)}</span>. Tiền sẽ được giữ lại cho đến khi vấn đề được giải quyết.
            </p>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-1.5">Lý do khiếu nại</label>
                <textarea
                  value={disputeReason}
                  onChange={(e) => setDisputeReason(e.target.value)}
                  placeholder="Vui lòng mô tả chi tiết vấn đề bạn gặp phải (ví dụ: Sản phẩm không đúng mô tả, tài khoản bị lỗi...)"
                  className="w-full h-32 bg-[#141414] border border-white/10 rounded-xl p-3 text-white text-sm focus:outline-none focus:border-red-500 resize-none"
                />
              </div>

              <div className="flex gap-3 justify-end pt-2">
                <button
                  onClick={() => setShowDisputeModal(false)}
                  className="px-4 py-2 rounded-lg bg-white/5 text-gray-300 font-medium text-sm hover:bg-white/10 transition-colors"
                >
                  Hủy bỏ
                </button>
                <button
                  onClick={handleCreateDispute}
                  disabled={isSubmittingDispute || !disputeReason.trim()}
                  className="px-4 py-2 rounded-lg bg-red-600 text-white font-medium text-sm hover:bg-red-700 transition-colors disabled:opacity-50 flex items-center gap-2"
                >
                  {isSubmittingDispute ? 'Đang gửi...' : 'Gửi khiếu nại'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
