"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter, useParams } from "next/navigation";
import {
  ArrowLeft,
  Loader2,
  Play,
  Send,
  User,
  CheckCircle,
  AlertTriangle,
  RefreshCw,
  Package,
  ChevronRight,
  Star,
  X,
  Upload,
  File as FileIcon,
  Download,
  Paperclip,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

// ── Types ──
interface OrderListing {
  id: string;
  title: string;
  category: string;
  subcategory?: string;
  priceFlh: number;
  description?: string;
  deliveryDays?: number;
}

interface OrderParty {
  id: string;
  name: string;
  email: string;
  avatar?: string | null;
}

interface ChatMessage {
  from: string;
  text: string;
  timestamp: string;
}

interface DeliveryFile {
  name: string;
  size: number;
  url: string;
}

interface OrderDetail {
  id: string;
  listingId: string;
  buyerId: string;
  sellerId: string;
  status: string;
  amountFlh: number;
  platformFee: number;
  sellerPayout: number;
  packageName?: string | null;
  createdAt: string;
  listing: OrderListing;
  buyer: OrderParty;
  seller: OrderParty;
  messages: ChatMessage[];
  deliveryFiles: DeliveryFile[];
}

// ── Status helpers ──
const STATUS_COLORS: Record<string, { bg: string; text: string; label: string }> = {
  pending: { bg: "bg-gray-800/60", text: "text-gray-400", label: "Pending" },
  paid: { bg: "bg-blue-900/20 border border-blue-700/30", text: "text-blue-400", label: "Paid" },
  in_progress: { bg: "bg-amber-900/20 border border-amber-700/30", text: "text-amber-400", label: "In Progress" },
  delivered: { bg: "bg-purple-900/20 border border-purple-700/30", text: "text-purple-400", label: "Delivered" },
  completed: { bg: "bg-emerald-900/20 border border-emerald-700/30", text: "text-emerald-400", label: "Completed" },
  disputed: { bg: "bg-red-900/20 border border-red-700/30", text: "text-red-400", label: "Disputed" },
  cancelled: { bg: "bg-gray-800/40 border border-gray-700/30", text: "text-gray-500", label: "Cancelled" },
};

function getStatusStyle(status: string) {
  return STATUS_COLORS[status] || STATUS_COLORS.pending;
}

// ── Progress stepper ──
const STEPS = ["Ordered", "Paid", "In Progress", "Delivered", "Completed"];

function getStepIndex(status: string): number {
  switch (status) {
    case "pending":
      return 0;
    case "paid":
      return 1;
    case "in_progress":
      return 2;
    case "delivered":
      return 3;
    case "completed":
      return 4;
    default:
      return -1;
  }
}

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString("en-MY", {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function formatShortDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString("en-MY", {
    month: "short",
    day: "numeric",
  });
}

// ── Component ──
export default function OrderDetailPage() {
  const { user, token, loading } = useAuth();
  const router = useRouter();
  const params = useParams();
  const orderId = params.id as string;

  const [order, setOrder] = useState<OrderDetail | null>(null);
  const [loadingData, setLoadingData] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Message input
  const [messageText, setMessageText] = useState("");
  const [sendingMsg, setSendingMsg] = useState(false);
  const [msgError, setMsgError] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Action button state
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);

  // Review state
  const [hasReviewed, setHasReviewed] = useState(false);
  const [showReviewForm, setShowReviewForm] = useState(false);
  const [reviewRating, setReviewRating] = useState(0);
  const [reviewTitle, setReviewTitle] = useState("");
  const [reviewText, setReviewText] = useState("");
  const [submittingReview, setSubmittingReview] = useState(false);
  const [reviewSubmitted, setReviewSubmitted] = useState(false);
  const [reviewError, setReviewError] = useState<string | null>(null);

  // Upload state
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadError, setUploadError] = useState<string | null>(null);

  const isBuyer = user?.id === order?.buyerId;
  const isSeller = user?.id === order?.sellerId;

  // ── Auth redirect ──
  useEffect(() => {
    if (!loading && !token) {
      router.push("/auth");
    }
  }, [loading, token, router]);

  // ── Fetch order ──
  const fetchOrder = useCallback(async () => {
    if (!token || !orderId) return;
    setLoadingData(true);
    setError(null);
    try {
      const res = await fetch(`/mobile/api/souq/orders/${orderId}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      const data = await res.json();
      if (res.ok) {
        setOrder(data.order);
        if (data.hasReviewed !== undefined) {
          setHasReviewed(data.hasReviewed);
        }
        setReviewSubmitted(false);
        setShowReviewForm(false);
      } else {
        setError(data.error || "Failed to load order");
      }
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setLoadingData(false);
    }
  }, [token, orderId]);

  useEffect(() => {
    if (token && orderId) fetchOrder();
  }, [token, orderId, fetchOrder]);

  // ── Scroll to bottom on new messages ──
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [order?.messages]);

  // ── Send message ──
  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!messageText.trim() || !token || !orderId) return;

    setSendingMsg(true);
    setMsgError(null);

    try {
      const res = await fetch(`/mobile/api/souq/orders/${orderId}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ message: messageText.trim() }),
      });

      const data = await res.json();
      if (res.ok) {
        setOrder(data.order);
        setMessageText("");
      } else {
        setMsgError(data.error || "Failed to send message");
      }
    } catch {
      setMsgError("Network error. Please try again.");
    } finally {
      setSendingMsg(false);
    }
  };

  // ── Action buttons ──
  const handleAction = async (action: string) => {
    if (!token || !orderId) return;

    setActionLoading(action);
    setActionError(null);

    try {
      let body: Record<string, unknown> = {};

      if (action === "confirm_delivery") {
        body = { status: "completed" };
      } else if (action === "request_revision") {
        body = { status: "disputed" };
      } else if (action === "start_order") {
        body = { status: "in_progress" };
      } else if (action === "mark_delivered") {
        body = { status: "delivered" };
      }

      const res = await fetch(`/mobile/api/souq/orders/${orderId}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(body),
      });

      const data = await res.json();
      if (res.ok) {
        setOrder(data.order);
      } else {
        setActionError(data.error || "Failed to update order");
      }
    } catch {
      setActionError("Network error. Please try again.");
    } finally {
      setActionLoading(null);
    }
  };

  // ── Submit Review ──
  const handleSubmitReview = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token || !order || reviewRating === 0) return;

    setSubmittingReview(true);
    setReviewError(null);

    try {
      const res = await fetch("/mobile/api/souq/reviews", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          listingId: order.listingId,
          orderId: order.id,
          rating: reviewRating,
          title: reviewTitle.trim() || undefined,
          text: reviewText.trim() || undefined,
        }),
      });

      const data = await res.json();
      if (res.ok) {
        setReviewSubmitted(true);
        setHasReviewed(true);
        setShowReviewForm(false);
      } else {
        setReviewError(data.error || "Failed to submit review");
      }
    } catch {
      setReviewError("Network error. Please try again.");
    } finally {
      setSubmittingReview(false);
    }
  };

  // ── Upload delivery file ──
  const handleUploadFile = async () => {
    if (!selectedFile || !token || !orderId) return;

    setUploading(true);
    setUploadProgress(0);
    setUploadError(null);

    // Simulate progress
    const progressInterval = setInterval(() => {
      setUploadProgress((prev) => {
        if (prev >= 90) {
          clearInterval(progressInterval);
          return 90;
        }
        return prev + 10;
      });
    }, 200);

    try {
      const formData = new FormData();
      formData.append("file", selectedFile);
      formData.append("orderId", orderId);

      const res = await fetch("/mobile/api/souq/upload", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: formData,
      });

      clearInterval(progressInterval);

      const data = await res.json();
      if (res.ok) {
        setUploadProgress(100);

        // Build updated delivery files list
        const newFile: DeliveryFile = {
          name: data.name,
          size: data.size,
          url: data.url,
        };
        const updatedFiles = [...(order?.deliveryFiles || []), newFile];

        // Persist to order via PATCH
        const patchRes = await fetch(
          `/mobile/api/souq/orders/${orderId}`,
          {
            method: "PATCH",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${token}`,
            },
            body: JSON.stringify({ deliveryFiles: updatedFiles }),
          }
        );

        const patchData = await patchRes.json();
        if (patchRes.ok) {
          setOrder(patchData.order);
        } else {
          setUploadError(
            patchData.error || "Failed to save file metadata"
          );
        }

        setSelectedFile(null);
      } else {
        setUploadError(data.error || "Upload failed");
      }
    } catch {
      clearInterval(progressInterval);
      setUploadError("Network error. Please try again.");
    } finally {
      setUploading(false);
    }
  };

  // ── Render ──
  if (loading) {
    return (
      <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
      </div>
    );
  }

  if (!user) return null;

  const sc = order ? getStatusStyle(order.status) : null;
  const stepIdx = order ? getStepIndex(order.status) : -1;
  const total = order ? order.amountFlh + order.platformFee : 0;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-28">
      {/* Sticky header */}
      <div className="sticky top-0 z-20 bg-[#0a0a0f]/90 backdrop-blur-lg border-b border-gray-800/40">
        <div className="flex items-center gap-3 px-4 h-12">
          <button
            onClick={() => router.push("/souq/orders")}
            className="w-8 h-8 rounded-full bg-gray-800/60 flex items-center justify-center active:bg-gray-700/60 transition"
          >
            <ArrowLeft size={16} className="text-gray-400" />
          </button>
          <h1 className="text-sm font-semibold text-white truncate">
            Order Details
          </h1>
        </div>
      </div>

      {loadingData ? (
        <div className="flex flex-col items-center justify-center py-20">
          <Loader2 size={32} className="text-[#D4AF37] animate-spin mb-3" />
          <p className="text-sm text-gray-500">Loading order...</p>
        </div>
      ) : error ? (
        <ErrorFeedback error={error} kind="network" onRetry={fetchOrder} context="order detail" />
      ) : !order ? (
        <div className="mx-4 mt-4 bg-gray-900/40 border border-gray-800/60 rounded-2xl p-6 text-center">
          <p className="text-sm text-gray-400">Order not found</p>
          <button
            onClick={() => router.push("/souq/orders")}
            className="mt-3 text-xs text-[#D4AF37] underline"
          >
            Back to orders
          </button>
        </div>
      ) : (
        <div className="px-4 pt-4 space-y-4 animate-fade-in">
          {/* ── Order Header ── */}
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
            <div className="flex items-start justify-between gap-3 mb-3">
              <div className="flex-1 min-w-0">
                <h2 className="text-base font-bold text-white leading-tight mb-1">
                  {order.listing.title}
                </h2>
                <p className="text-xs text-gray-500 font-mono">
                  #{order.id.slice(0, 8)}
                </p>
              </div>
              {sc && (
                <span
                  className={`shrink-0 text-[10px] font-medium px-2.5 py-1 rounded-full ${sc.bg} ${sc.text}`}
                >
                  {sc.label}
                </span>
              )}
            </div>

            {/* Seller/Buyer info */}
            <div className="flex items-center gap-3 mt-3 pt-3 border-t border-gray-800/40">
              <div className="flex items-center gap-2 flex-1 min-w-0">
                <div className="w-8 h-8 rounded-full bg-gradient-to-br from-gray-700 to-gray-800 flex items-center justify-center shrink-0">
                  <span className="text-[10px] font-bold text-gray-300">
                    {(isBuyer ? order.seller.name : order.buyer.name).charAt(0).toUpperCase()}
                  </span>
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-gray-500">
                    {isBuyer ? "Seller" : "Buyer"}
                  </p>
                  <p className="text-sm font-semibold text-white truncate">
                    {isBuyer ? order.seller.name : order.buyer.name}
                  </p>
                </div>
              </div>
              <span className="text-[10px] text-gray-600">
                {formatDate(order.createdAt)}
              </span>
            </div>
          </div>

          {/* ── Progress Stepper ── */}
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
            <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">
              Progress
            </h3>
            <div className="flex items-start justify-between">
              {STEPS.map((label, i) => {
                const isCompleted = i < stepIdx;
                const isCurrent = i === stepIdx;
                const isUpcoming = i > stepIdx;

                return (
                  <div key={label} className="flex flex-col items-center flex-1">
                    {/* Circle */}
                    <div
                      className={`relative w-7 h-7 rounded-full flex items-center justify-center transition-all ${
                        isCompleted
                          ? "bg-emerald-500/20 border-2 border-emerald-500"
                          : isCurrent
                            ? "bg-[#D4AF37]/20 border-2 border-[#D4AF37]"
                            : "bg-gray-800/60 border-2 border-gray-700/60"
                      }`}
                    >
                      {isCompleted ? (
                        <CheckCircle size={14} className="text-emerald-400" />
                      ) : isCurrent ? (
                        <span className="w-2 h-2 rounded-full bg-[#D4AF37] animate-pulse" />
                      ) : (
                        <span className="w-2 h-2 rounded-full bg-gray-600" />
                      )}
                    </div>

                    {/* Label */}
                    <span
                      className={`text-[9px] mt-1.5 text-center leading-tight max-w-[60px] ${
                        isCompleted
                          ? "text-emerald-400"
                          : isCurrent
                            ? "text-[#D4AF37] font-semibold"
                            : "text-gray-600"
                      }`}
                    >
                      {label}
                    </span>

                    {/* Connector line */}
                    {i < STEPS.length - 1 && (
                      <div
                        className={`absolute mt-3.5 left-[calc(50%+14px)] w-[calc(100%-28px)] h-[2px] ${
                          i < stepIdx ? "bg-emerald-500/60" : "bg-gray-800/60"
                        }`}
                        style={{
                          position: "absolute",
                          top: "14px",
                          left: "calc(50% + 14px)",
                          width: "calc(100% - 28px)",
                          height: "2px",
                        }}
                      />
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Order Details ── */}
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
            <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
              Order Details
            </h3>
            <div className="space-y-2.5">
              {order.packageName && (
                <div className="flex items-center justify-between">
                  <span className="text-xs text-gray-500">Package</span>
                  <span className="text-xs font-medium text-white">
                    {order.packageName}
                  </span>
                </div>
              )}
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-500">Amount (FLH)</span>
                <span className="text-sm font-bold text-[#D4AF37]">
                  {order.amountFlh.toLocaleString()} FLH
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-500">Platform Fee</span>
                <span className="text-xs text-gray-400">
                  -{order.platformFee.toLocaleString()} FLH
                </span>
              </div>
              {order.listing.deliveryDays && (
                <div className="flex items-center justify-between">
                  <span className="text-xs text-gray-500">Delivery time</span>
                  <span className="text-xs text-gray-400">
                    Up to {order.listing.deliveryDays} days
                  </span>
                </div>
              )}
              <div className="pt-2 mt-2 border-t border-gray-800/40 flex items-center justify-between">
                <span className="text-xs font-semibold text-gray-400">Total Charged</span>
                <span className="text-sm font-bold text-white">
                  {total.toLocaleString()} FLH
                </span>
              </div>
            </div>
          </div>

          {/* ── Action Buttons ── */}
          {order.status === "delivered" && isBuyer && (
            <div className="space-y-2.5">
              {actionError && (
                <ErrorFeedback error={actionError} kind="default" onRetry={() => setActionError(null)} context="action" />
              )}
              <button
                onClick={() => handleAction("confirm_delivery")}
                disabled={actionLoading !== null}
                className="w-full flex items-center justify-center gap-2 py-4 rounded-xl bg-emerald-600/20 border border-emerald-500/40 text-emerald-400 font-semibold text-sm active:bg-emerald-600/30 transition disabled:opacity-50 min-h-[48px]"
              >
                {actionLoading === "confirm_delivery" ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  <CheckCircle size={16} />
                )}
                ✓ Confirm Delivery
              </button>
              <button
                onClick={() => handleAction("request_revision")}
                disabled={actionLoading !== null}
                className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl bg-amber-900/10 border border-amber-700/30 text-amber-400 font-medium text-sm active:bg-amber-900/20 transition disabled:opacity-50 min-h-[48px]"
              >
                {actionLoading === "request_revision" ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  <RefreshCw size={16} />
                )}
                ↻ Request Revision
              </button>
            </div>
          )}

          {order.status === "paid" && isSeller && (
            <div className="space-y-2.5">
              {actionError && (
                <ErrorFeedback error={actionError} kind="default" onRetry={() => setActionError(null)} context="action" />
              )}
              <button
                onClick={() => handleAction("start_order")}
                disabled={actionLoading !== null}
                className="w-full flex items-center justify-center gap-2 py-4 rounded-xl bg-emerald-600/20 border border-emerald-500/40 text-emerald-400 font-semibold text-sm active:bg-emerald-600/30 transition disabled:opacity-50 min-h-[48px]"
              >
                {actionLoading === "start_order" ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  <Play size={16} />
                )}
                ▶ Start Order
              </button>
            </div>
          )}

          {order.status === "in_progress" && !isSeller && (
            <div className="bg-amber-900/10 border border-amber-700/30 rounded-2xl p-4 flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-amber-900/20 flex items-center justify-center shrink-0">
                <Loader2 size={16} className="text-amber-400 animate-spin" />
              </div>
              <div>
                <p className="text-sm font-medium text-amber-300">
                  In Progress
                </p>
                <p className="text-xs text-amber-400/60">
                  Awaiting delivery from {isBuyer ? order.seller.name : "you"}
                </p>
              </div>
            </div>
          )}

          {order.status === "in_progress" && isSeller && (
            <div className="space-y-2.5">
              {actionError && (
                <ErrorFeedback error={actionError} kind="default" onRetry={() => setActionError(null)} context="action" />
              )}
              <button
                onClick={() => handleAction("mark_delivered")}
                disabled={actionLoading !== null}
                className="w-full flex items-center justify-center gap-2 py-4 rounded-xl bg-purple-600/20 border border-purple-500/40 text-purple-400 font-semibold text-sm active:bg-purple-600/30 transition disabled:opacity-50 min-h-[48px]"
              >
                {actionLoading === "mark_delivered" ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  <Send size={16} />
                )}
                📦 Mark as Delivered
              </button>
            </div>
          )}

          {/* ── Seller: Upload Delivery Files ── */}
          {isSeller && order.status === "in_progress" && (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
              <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4 flex items-center gap-2">
                <Paperclip size={14} className="text-[#D4AF37]" />
                Upload Delivery Files
              </h3>

              {/* File list */}
              {order.deliveryFiles.length > 0 && (
                <div className="space-y-2 mb-4">
                  {order.deliveryFiles.map((file, idx) => (
                    <a
                      key={idx}
                      href={file.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-3 bg-[#1a1a24] border border-gray-800/60 rounded-xl p-3 hover:border-[#D4AF37]/30 transition group"
                    >
                      <div className="w-8 h-8 rounded-lg bg-[#D4AF37]/10 flex items-center justify-center shrink-0">
                        <FileIcon size={16} className="text-[#D4AF37]" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-white truncate group-hover:text-[#D4AF37] transition">
                          {file.name}
                        </p>
                        <p className="text-[10px] text-gray-500">
                          {(file.size / 1024).toFixed(1)} KB
                        </p>
                      </div>
                      <Download size={14} className="text-gray-500 group-hover:text-[#D4AF37] transition shrink-0" />
                    </a>
                  ))}
                </div>
              )}

              {/* Upload form */}
              <div className="space-y-3">
                <div className="relative">
                  <input
                    type="file"
                    id="delivery-file-input"
                    accept="image/*,.pdf,.zip,.rar,.7z,.gz"
                    onChange={(e) => {
                      setSelectedFile(e.target.files?.[0] || null);
                      setUploadError(null);
                    }}
                    className="hidden"
                  />
                  <label
                    htmlFor="delivery-file-input"
                    className={`flex items-center gap-3 w-full bg-[#1a1a24] border border-dashed border-gray-700/60 rounded-xl p-4 cursor-pointer hover:border-[#D4AF37]/40 transition ${
                      selectedFile ? "border-[#D4AF37]/40" : ""
                    }`}
                  >
                    <div className="w-9 h-9 rounded-xl bg-[#D4AF37]/10 flex items-center justify-center shrink-0">
                      <Upload size={16} className="text-[#D4AF37]" />
                    </div>
                    <div className="flex-1 min-w-0">
                      {selectedFile ? (
                        <>
                          <p className="text-sm font-medium text-white truncate">
                            {selectedFile.name}
                          </p>
                          <p className="text-[10px] text-gray-500">
                            {(selectedFile.size / 1024).toFixed(1)} KB
                          </p>
                        </>
                      ) : (
                        <>
                          <p className="text-sm font-medium text-gray-400">
                            Tap to select a file
                          </p>
                          <p className="text-[10px] text-gray-600">
                            Images, PDFs, ZIPs — max 10 MB
                          </p>
                        </>
                      )}
                    </div>
                    {selectedFile && (
                      <button
                        type="button"
                        onClick={(e) => {
                          e.preventDefault();
                          setSelectedFile(null);
                          setUploadError(null);
                        }}
                        className="w-7 h-7 rounded-full bg-gray-800/60 flex items-center justify-center active:bg-gray-700/60 transition"
                      >
                        <X size={12} className="text-gray-400" />
                      </button>
                    )}
                  </label>
                </div>

                {/* Upload progress */}
                {uploading && (
                  <div className="w-full bg-gray-800/60 rounded-full h-2 overflow-hidden">
                    <div
                      className="h-full bg-[#D4AF37] rounded-full transition-all duration-300"
                      style={{ width: `${uploadProgress}%` }}
                    />
                  </div>
                )}

                {uploadError && (
                  <p className="text-xs text-red-400">{uploadError}</p>
                )}

                <button
                  onClick={handleUploadFile}
                  disabled={!selectedFile || uploading}
                  className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl bg-[#D4AF37] text-[#0a0a0f] font-semibold text-sm active:opacity-80 transition disabled:opacity-40 min-h-[48px]"
                >
                  {uploading ? (
                    <>
                      <Loader2 size={16} className="animate-spin" />
                      Uploading... {uploadProgress}%
                    </>
                  ) : (
                    <>
                      <Upload size={16} />
                      Upload File
                    </>
                  )}
                </button>
              </div>
            </div>
          )}

          {/* ── Buyer: Delivery Files ── */}
          {isBuyer && order.deliveryFiles.length > 0 && (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
              <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4 flex items-center gap-2">
                <Paperclip size={14} className="text-[#D4AF37]" />
                Delivery Files
              </h3>
              <div className="space-y-2">
                {order.deliveryFiles.map((file, idx) => (
                  <a
                    key={idx}
                    href={file.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-3 bg-[#1a1a24] border border-gray-800/60 rounded-xl p-3 hover:border-[#D4AF37]/30 transition group"
                  >
                    <div className="w-8 h-8 rounded-lg bg-[#D4AF37]/10 flex items-center justify-center shrink-0">
                      <FileIcon size={16} className="text-[#D4AF37]" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-white truncate group-hover:text-[#D4AF37] transition">
                        {file.name}
                      </p>
                      <p className="text-[10px] text-gray-500">
                        {(file.size / 1024).toFixed(1)} KB
                      </p>
                    </div>
                    <Download size={14} className="text-gray-500 group-hover:text-[#D4AF37] transition shrink-0" />
                  </a>
                ))}
              </div>
            </div>
          )}

          {order.status === "completed" && (
            <>
              <div className="bg-emerald-900/15 border border-emerald-700/30 rounded-2xl p-4 flex items-center gap-3">
                <div className="w-8 h-8 rounded-full bg-emerald-900/20 flex items-center justify-center shrink-0">
                  <CheckCircle size={18} className="text-emerald-400" />
                </div>
                <div>
                  <p className="text-sm font-bold text-emerald-400">
                    ✓ Order Completed
                  </p>
                  <p className="text-xs text-emerald-400/60">
                    This order has been completed successfully.
                  </p>
                </div>
              </div>

              {/* ── Review Section ── */}
              {isBuyer && (
                <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
                  {reviewSubmitted ? (
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-full bg-emerald-900/20 flex items-center justify-center shrink-0">
                        <CheckCircle size={20} className="text-emerald-400" />
                      </div>
                      <div>
                        <p className="text-sm font-bold text-emerald-400">Review Submitted!</p>
                        <p className="text-xs text-emerald-400/60">Thank you for your feedback.</p>
                      </div>
                    </div>
                  ) : hasReviewed ? (
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-full bg-[#D4AF37]/15 flex items-center justify-center shrink-0">
                        <Star size={18} className="text-[#D4AF37]" />
                      </div>
                      <div>
                        <p className="text-sm font-bold text-[#D4AF37]">You reviewed this order</p>
                        <p className="text-xs text-gray-500">Your rating has been recorded.</p>
                      </div>
                    </div>
                  ) : !showReviewForm ? (
                    <button
                      onClick={() => setShowReviewForm(true)}
                      className="w-full flex items-center justify-center gap-2 py-4 rounded-xl bg-[#D4AF37]/15 border border-[#D4AF37]/30 text-[#D4AF37] font-semibold text-sm active:bg-[#D4AF37]/25 transition min-h-[48px]"
                    >
                      <Star size={16} />
                      Write a Review
                    </button>
                  ) : (
                    <form onSubmit={handleSubmitReview} className="space-y-4">
                      <div className="flex items-center justify-between mb-1">
                        <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
                          Write a Review
                        </h3>
                        <button
                          type="button"
                          onClick={() => {
                            setShowReviewForm(false);
                            setReviewError(null);
                          }}
                          className="w-7 h-7 rounded-full bg-gray-800/60 flex items-center justify-center active:bg-gray-700/60 transition"
                        >
                          <X size={14} className="text-gray-400" />
                        </button>
                      </div>

                      {/* Star rating */}
                      <div>
                        <label className="block text-xs text-gray-500 mb-2">Rating</label>
                        <div className="flex items-center gap-1.5">
                          {[1, 2, 3, 4, 5].map((star) => (
                            <button
                              key={star}
                              type="button"
                              onClick={() => setReviewRating(star)}
                              className="p-1 transition active:scale-90"
                            >
                              <Star
                                size={24}
                                className={`transition ${
                                  star <= reviewRating
                                    ? "fill-[#D4AF37] text-[#D4AF37]"
                                    : "text-gray-600 fill-none"
                                }`}
                              />
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Title */}
                      <div>
                        <label className="block text-xs text-gray-500 mb-1.5">Title (optional)</label>
                        <input
                          type="text"
                          value={reviewTitle}
                          onChange={(e) => setReviewTitle(e.target.value)}
                          placeholder="Summarize your experience..."
                          maxLength={200}
                          className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 transition"
                        />
                      </div>

                      {/* Text */}
                      <div>
                        <label className="block text-xs text-gray-500 mb-1.5">Review (optional)</label>
                        <textarea
                          value={reviewText}
                          onChange={(e) => setReviewText(e.target.value)}
                          placeholder="Describe your experience with this service..."
                          maxLength={2000}
                          rows={4}
                          className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 transition resize-none"
                        />
                      </div>

                      {/* Submit */}
                      {reviewError && (
                        <p className="text-xs text-red-400">{reviewError}</p>
                      )}
                      <button
                        type="submit"
                        disabled={submittingReview || reviewRating === 0}
                        className="w-full flex items-center justify-center gap-2 py-4 rounded-xl bg-[#D4AF37] text-[#0a0a0f] font-semibold text-sm active:opacity-80 transition disabled:opacity-40 min-h-[48px]"
                      >
                        {submittingReview ? (
                          <Loader2 size={16} className="animate-spin" />
                        ) : (
                          <Star size={16} />
                        )}
                        Submit Review
                      </button>
                    </form>
                  )}
                </div>
              )}
            </>
          )}

          {/* ── Chat / Messages ── */}
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl overflow-hidden">
            <div className="px-5 pt-4 pb-2 border-b border-gray-800/40">
              <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
                Messages
              </h3>
            </div>

            {/* Messages list */}
            <div className="px-4 py-3 space-y-3 max-h-[320px] overflow-y-auto">
              {order.messages.length === 0 ? (
                <div className="text-center py-6">
                  <p className="text-xs text-gray-600">
                    No messages yet. Start a conversation.
                  </p>
                </div>
              ) : (
                order.messages.map((msg, idx) => {
                  const isFromSeller = msg.from === order.sellerId;
                  const isFromBuyer = msg.from === order.buyerId;
                  const isMine =
                    (isBuyer && isFromBuyer) || (isSeller && isFromSeller);

                  return (
                    <div
                      key={idx}
                      className={`flex ${isMine ? "justify-end" : "justify-start"}`}
                    >
                      <div
                        className={`max-w-[80%] rounded-2xl px-3.5 py-2.5 ${
                          isMine
                            ? "bg-[#D4AF37]/15 border border-[#D4AF37]/20 rounded-br-md"
                            : "bg-gray-800/60 border border-gray-700/40 rounded-bl-md"
                        }`}
                      >
                        {/* Sender name (opposite side) */}
                        {!isMine && (
                          <p className="text-[10px] font-medium text-gray-500 mb-0.5">
                            {isFromSeller ? order.seller.name : order.buyer.name}
                          </p>
                        )}
                        <p className="text-sm text-gray-200 whitespace-pre-wrap break-words">
                          {msg.text}
                        </p>
                        <p
                          className={`text-[9px] mt-0.5 ${
                            isMine ? "text-right text-[#D4AF37]/50" : "text-left text-gray-600"
                          }`}
                        >
                          {formatShortDate(msg.timestamp)}
                        </p>
                      </div>
                    </div>
                  );
                })
              )}
              <div ref={messagesEndRef} />
            </div>

            {/* Message input */}
            <form
              onSubmit={handleSendMessage}
              className="border-t border-gray-800/40 px-4 py-3 flex items-end gap-2"
            >
              <div className="flex-1">
                <input
                  type="text"
                  value={messageText}
                  onChange={(e) => setMessageText(e.target.value)}
                  placeholder="Type a message..."
                  maxLength={2000}
                  className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 transition min-h-[44px]"
                />
                {msgError && (
                  <p className="text-[10px] text-red-400 mt-1">{msgError}</p>
                )}
              </div>
              <button
                type="submit"
                disabled={sendingMsg || !messageText.trim()}
                className="w-11 h-11 rounded-xl bg-[#D4AF37] text-[#0a0a0f] flex items-center justify-center active:opacity-80 transition disabled:opacity-40 shrink-0"
              >
                {sendingMsg ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  <Send size={16} />
                )}
              </button>
            </form>
          </div>

          {/* ── Party Info Cards ── */}
          <div className="grid grid-cols-2 gap-3">
            {/* Buyer info */}
            {!isBuyer && (
              <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4">
                <p className="text-[10px] text-gray-500 uppercase tracking-wider mb-2 font-medium">
                  Buyer
                </p>
                <div className="flex items-center gap-2.5">
                  <div className="w-9 h-9 rounded-full bg-gradient-to-br from-gray-700 to-gray-800 flex items-center justify-center shrink-0">
                    <span className="text-xs font-bold text-gray-300">
                      {order.buyer.name.charAt(0).toUpperCase()}
                    </span>
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-white truncate">
                      {order.buyer.name}
                    </p>
                    <p className="text-[10px] text-gray-600 truncate">
                      {order.buyer.email}
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* Seller info */}
            {!isSeller && (
              <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4">
                <p className="text-[10px] text-gray-500 uppercase tracking-wider mb-2 font-medium">
                  Seller
                </p>
                <div className="flex items-center gap-2.5">
                  <div className="w-9 h-9 rounded-full bg-gradient-to-br from-gray-700 to-gray-800 flex items-center justify-center shrink-0">
                    <span className="text-xs font-bold text-gray-300">
                      {order.seller.name.charAt(0).toUpperCase()}
                    </span>
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-white truncate">
                      {order.seller.name}
                    </p>
                    <p className="text-[10px] text-gray-600 truncate">
                      {order.seller.email}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
