"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { orderApi, refundApi, reviewApi, getBackendBaseUrl } from "@/lib/api";
import { useMarket } from "@/context/MarketContext";
import { useSnackbar } from "@/context/SnackbarContext";
import { confirmDelete } from "@/lib/sweetAlert";
import { Store, Truck, AlertCircle, XCircle, RotateCcw, Clock, Star, CreditCard } from "lucide-react";
import { openCourierTracking, getCourierCn, hasCourierTracking } from "@/lib/courier";
import { normalizePhonePk } from "@/lib/validators";

const ONLINE_METHODS = ["jazzcash", "jazzcash_partial", "stripe", "easypaisa", "paypal"];

function handlePaymentRedirect(res) {
  if (res?.checkout_url) {
    if (res.checkout_method === "POST" && res.checkout_params) {
      const form = document.createElement("form");
      form.method = "POST";
      form.action = res.checkout_url;
      Object.entries(res.checkout_params).forEach(([k, v]) => {
        const inp = document.createElement("input");
        inp.type = "hidden";
        inp.name = k;
        inp.value = v ?? "";
        form.appendChild(inp);
      });
      document.body.appendChild(form);
      form.submit();
      return true;
    }
    window.location.href = res.checkout_url;
    return true;
  }
  return false;
}

export default function OrderDetail({ orderId }) {
  const { formatPrice } = useMarket();
  const { showSuccess, showError } = useSnackbar();
  const searchParams = useSearchParams();
  const router = useRouter();
  const [order, setOrder] = useState(null);
  const [loading, setLoading] = useState(true);
  const [refundLoading, setRefundLoading] = useState(false);
  const [refundAmount, setRefundAmount] = useState("");
  const [cancelLoading, setCancelLoading] = useState(false);
  const [payLoading, setPayLoading] = useState(false);
  const [payPhone, setPayPhone] = useState("");
  const [payCnic, setPayCnic] = useState("");
  const [editingNotes, setEditingNotes] = useState(false);
  const [customerNotes, setCustomerNotes] = useState("");
  const [notesSaving, setNotesSaving] = useState(false);
  const [showReviewForm, setShowReviewForm] = useState(false);
  const [reviewRating, setReviewRating] = useState(5);
  const [reviewTitle, setReviewTitle] = useState("");
  const [reviewBody, setReviewBody] = useState("");
  const [selectedProductIds, setSelectedProductIds] = useState([]);
  const [reviewSubmitting, setReviewSubmitting] = useState(false);
  const [reviewedProductIds, setReviewedProductIds] = useState([]);

  const loadOrder = () =>
    orderApi.get(orderId).then((res) => {
      const o = res.order;
      setOrder(o);
      setCustomerNotes(o?.customer_notes ?? "");
      const ids = (o?.items || [])
        .filter((i) => parseFloat(i.price) > 0 && i.product_id)
        .map((i) => i.product_id);
      setSelectedProductIds([...new Set(ids)]);
      if (!payPhone) {
        const guess = o?.shipping_address?.phone || o?.user?.phone || "";
        if (guess) setPayPhone(guess);
      }
      return o;
    });

  useEffect(() => {
    if (!orderId) return;
    loadOrder()
      .catch(() => setOrder(null))
      .finally(() => setLoading(false));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orderId]);

  // After gateway return (?paid=1 / ?paid=0), refresh order status.
  useEffect(() => {
    const paid = searchParams?.get("paid");
    if (!orderId || paid == null) return;
    loadOrder()
      .then((o) => {
        if (paid === "1") {
          const ps = o?.payment_status;
          if (ps === "paid" || ps === "partial_paid") {
            showSuccess?.("Payment successful. Order is now processing.");
          } else {
            showSuccess?.("Payment submitted. Status will update shortly.");
          }
        } else if (paid === "0") {
          showError?.("Payment was cancelled. You can try Pay Now again.");
        }
        router.replace(`/customer/orders/${orderId}`, { scroll: false });
      })
      .catch(() => {});
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orderId, searchParams]);

  const orderStatus = order?.complete_order_status || order?.status;
  const canReview = order && ["completed"].includes(orderStatus);
  const reviewableItems = (() => {
    const seen = new Set();
    return (order?.items || []).filter((i) => {
      if (!(parseFloat(i.price) > 0 && i.product_id) || reviewedProductIds.includes(i.product_id)) return false;
      if (seen.has(i.product_id)) return false;
      seen.add(i.product_id);
      return true;
    });
  })();

  const toggleProduct = (productId) => {
    setSelectedProductIds((prev) =>
      prev.includes(productId) ? prev.filter((id) => id !== productId) : [...prev, productId]
    );
  };

  const selectAllProducts = () => {
    setSelectedProductIds([...new Set(reviewableItems.map((i) => i.product_id))]);
  };

  const submitReview = async (e) => {
    e.preventDefault();
    if (!selectedProductIds.length) {
      showError?.("Select at least one product to review");
      return;
    }
    if (!reviewBody.trim() && !reviewTitle.trim()) {
      showError?.("Please write a short review");
      return;
    }
    setReviewSubmitting(true);
    try {
      await reviewApi.create({
        order_id: order.id,
        product_ids: selectedProductIds,
        rating: reviewRating,
        title: reviewTitle.trim() || undefined,
        body: reviewBody.trim() || undefined,
      });
      setReviewedProductIds((prev) => [...new Set([...prev, ...selectedProductIds])]);
      setShowReviewForm(false);
      setReviewTitle("");
      setReviewBody("");
      setReviewRating(5);
      showSuccess?.("Review submitted. It will appear on the product page after admin approval.");
    } catch (err) {
      showError?.(err?.data?.message || err?.message || "Failed to submit review");
    } finally {
      setReviewSubmitting(false);
    }
  };

  const paymentStatus = order?.payment_status;
  const method = String(order?.payment_method || "").toLowerCase();
  const isJazzcashOrder = method === "jazzcash" || method === "jazzcash_partial";
  const canCancelDirect =
    order &&
    order.status === "pending" &&
    paymentStatus !== "paid" &&
    paymentStatus !== "partial_paid";
  const canRequestCancel =
    order &&
    ["processing", "approved"].includes(order.status) &&
    !["shipped", "delivered", "completed", "cancelled", "refunded", "cancellation_requested"].includes(order.status);
  const canPayNow =
    order &&
    order.status === "pending" &&
    paymentStatus === "pending" &&
    ONLINE_METHODS.includes(method);
  const canUpdateNotes = order && ["pending", "paid"].includes(order.status);

  const reloadOrder = () => loadOrder();

  const handlePayNow = async () => {
    setPayLoading(true);
    try {
      if (isJazzcashOrder) {
        const phone = normalizePhonePk(payPhone);
        if (!phone) {
          showError?.("Enter your JazzCash mobile as 03XXXXXXXXX");
          setPayLoading(false);
          return;
        }
        const cnicDigits = String(payCnic || "").replace(/\D/g, "");
        if (cnicDigits.length < 6) {
          showError?.("Enter CNIC for JazzCash (last 6 digits or full CNIC)");
          setPayLoading(false);
          return;
        }
      }
      const payload = {};
      if (payPhone?.trim()) payload.payment_phone = normalizePhonePk(payPhone) || payPhone.trim();
      if (payCnic?.trim()) payload.payment_cnic = payCnic.trim();
      const res = await orderApi.retryPayment(order.id, payload);
      if (handlePaymentRedirect(res)) return;
      if (res.payment_ok || res.payment_status === "paid" || res.payment_status === "partial_paid") {
        showSuccess?.(res.message || "Payment completed.");
        await reloadOrder();
        return;
      }
      showSuccess?.(res.message || "Payment status updated.");
      await reloadOrder();
    } catch (e) {
      showError?.(e?.data?.message || e?.message || "Could not start payment");
    } finally {
      setPayLoading(false);
    }
  };
  const saveNotes = async () => {
    if (!orderId || !customerNotes.trim()) return;
    setNotesSaving(true);
    try {
      const res = await orderApi.update(orderId, { customer_notes: customerNotes.trim() });
      setOrder(res.order);
      setEditingNotes(false);
      showSuccess?.("Notes updated");
    } catch (e) {
      showError?.(e?.data?.message || e?.message || "Failed to update notes");
    } finally {
      setNotesSaving(false);
    }
  };

  if (loading || !order) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-12">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/3" />
          <div className="h-48 bg-gray-100 rounded-xl" />
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 py-12">
      <Link href="/customer/orders" className="text-[#1790d7] text-sm hover:underline mb-4 inline-block">
        ← Back to Orders
      </Link>
      <div className="flex justify-between items-start mb-6 flex-wrap gap-3">
        <h1 className="text-2xl font-bold">Order {order.order_number}</h1>
        <span
          className={`px-4 py-2 rounded-xl text-sm font-medium capitalize ${
            ["completed", "delivered"].includes(order.complete_order_status || order.status)
              ? "bg-emerald-100 text-emerald-700"
              : (order.complete_order_status || order.status) === "cancelled"
              ? "bg-red-100 text-red-700"
              : (order.complete_order_status || order.status) === "refunded"
              ? "bg-slate-100 text-slate-700"
              : "bg-amber-100 text-amber-700"
          }`}
          title="Order status"
        >
          {(order.complete_order_status || order.status)?.replace(/_/g, " ")}
        </span>
      </div>

      {/* Unpaid online order — Pay Now */}
      {canPayNow && (
        <div className="mb-6 p-5 border border-[#1790d7]/30 bg-[#1790d7]/5 rounded-2xl space-y-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div>
              <h2 className="font-semibold text-gray-900 flex items-center gap-2">
                <CreditCard className="w-5 h-5 text-[#1790d7]" />
                Payment pending
              </h2>
              <p className="text-sm text-gray-600 mt-1">
                Your order is saved. Pay with{" "}
                <span className="font-medium capitalize">{String(order.payment_method || "").replace(/_/g, " ")}</span>{" "}
                to start processing.
              </p>
            </div>
            <span className="px-3 py-1 rounded-lg text-xs font-medium bg-amber-100 text-amber-800 capitalize">
              {(order.payment_status || "pending").replace(/_/g, " ")}
            </span>
          </div>

          {isJazzcashOrder && (
            <div className="grid sm:grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">JazzCash mobile *</label>
                <input
                  type="tel"
                  value={payPhone}
                  onChange={(e) => setPayPhone(e.target.value)}
                  placeholder="03XXXXXXXXX"
                  className="w-full px-3 py-2.5 rounded-xl border border-gray-200 text-sm bg-white"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">CNIC (last 6 or full) *</label>
                <input
                  type="text"
                  value={payCnic}
                  onChange={(e) => setPayCnic(e.target.value.replace(/\D/g, "").slice(0, 13))}
                  placeholder="Last 6 digits"
                  className="w-full px-3 py-2.5 rounded-xl border border-gray-200 text-sm bg-white"
                />
              </div>
            </div>
          )}

          <button
            type="button"
            onClick={handlePayNow}
            disabled={payLoading}
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-[#1790d7] text-white rounded-xl font-semibold hover:bg-[#1277b8] disabled:opacity-50"
          >
            <CreditCard className="w-4 h-4" />
            {payLoading ? "Opening payment…" : "Pay now"}
          </button>
        </div>
      )}

      {/* Order actions: Cancel / Request cancellation */}
      <div className="mb-6 flex flex-wrap gap-3">
        {canCancelDirect && (
          <button
            type="button"
            onClick={async () => {
              const confirmed = await confirmDelete({
                title: "Cancel this order?",
                text: "This unpaid order will be cancelled immediately.",
                confirmButtonText: "Yes, cancel order",
              });
              if (!confirmed) return;
              setCancelLoading(true);
              try {
                await orderApi.cancel(order.id);
                setOrder((o) => (o ? { ...o, status: "cancelled" } : o));
                showSuccess?.("Order cancelled");
              } catch (e) {
                showError?.(e?.data?.message || e?.message || "Could not cancel order");
              } finally {
                setCancelLoading(false);
              }
            }}
            disabled={cancelLoading}
            className="inline-flex items-center gap-2 px-4 py-2 border border-red-200 rounded-xl text-red-700 bg-red-50 hover:bg-red-100 font-medium disabled:opacity-50"
          >
            <XCircle className="w-4 h-4" />
            {cancelLoading ? "Cancelling..." : "Cancel order"}
          </button>
        )}
        {canRequestCancel && (
          <button
            type="button"
            onClick={async () => {
              const reason = typeof window !== "undefined"
                ? window.prompt("Reason for cancellation request:")
                : "";
              if (reason == null) return;
              if (!String(reason).trim()) {
                showError?.("Please provide a reason");
                return;
              }
              setCancelLoading(true);
              try {
                await orderApi.requestCancellation(order.id, { reason: String(reason).trim() });
                setOrder((o) => (o ? { ...o, status: "cancellation_requested" } : o));
                showSuccess?.("Cancellation requested. Waiting for seller approval.");
              } catch (e) {
                showError?.(e?.data?.message || e?.message || "Could not request cancellation");
              } finally {
                setCancelLoading(false);
              }
            }}
            disabled={cancelLoading}
            className="inline-flex items-center gap-2 px-4 py-2 border border-amber-200 rounded-xl text-amber-800 bg-amber-50 hover:bg-amber-100 font-medium disabled:opacity-50"
          >
            <XCircle className="w-4 h-4" />
            {cancelLoading ? "Submitting…" : "Request cancellation"}
          </button>
        )}
      </div>

      {order.status === "cancellation_requested" && (
        <div className="mb-6 p-4 bg-amber-50 border border-amber-200 rounded-xl text-sm text-amber-800">
          Cancellation requested — waiting for the seller to approve or reject.
          {order.cancellation_reason && (
            <p className="mt-1 text-amber-700">Your reason: {order.cancellation_reason}</p>
          )}
        </div>
      )}

      {/* Tracking: one Tracking ID per store/shipment */}
      {(order.shipments?.length > 0 || order.tracking_number || order.tracking_url) && (
        <div className="mb-6 space-y-4">
          <h3 className="font-semibold text-gray-900 flex items-center gap-2">
            <Truck className="w-5 h-5 text-[#1790d7]" />
            {order.shipments?.length > 1 ? "Track your shipments (by store)" : "Track order"}
          </h3>
          <p className="text-xs text-gray-500">
            Products from the same store share one Tracking ID. Different stores have separate Tracking IDs.
          </p>
          {order.shipments?.length > 0 ? (
            order.shipments.map((s) => (
              <div key={s.id} className="p-4 bg-blue-50 rounded-2xl border border-blue-100">
                <p className="text-sm font-semibold text-gray-900 mb-1">
                  {s.store?.name || s.store_name || "Store"} → Tracking ID:{" "}
                  <span className="font-mono text-[#1790d7]">
                    {getCourierCn(s) || s.tracking_number || "Pending"}
                  </span>
                </p>
                {(s.product_names && s.product_names.length > 0) && (
                  <p className="text-sm text-gray-700 mb-1">
                    <span className="font-medium">Products:</span> {s.product_names.join(", ")}
                  </p>
                )}
                {s.carrier && (
                  <p className="text-sm text-gray-600 mb-1">Courier: <span className="font-medium">{s.carrier}</span></p>
                )}
                {s.shipping_cost != null && Number(s.shipping_cost) > 0 && (
                  <p className="text-sm text-gray-600 mb-1">
                    Shipping: <span className="font-medium">{formatPrice(s.shipping_cost)}</span>
                  </p>
                )}
                {s.lcs_status && (
                  <p className="text-xs text-gray-500 mb-1">Status: {s.lcs_status.replace(/_/g, " ")}</p>
                )}
                {hasCourierTracking(s) && (
                  <button
                    type="button"
                    onClick={() => {
                      openCourierTracking(s);
                      showSuccess("Tracking ID copied. Paste it on the courier tracking page.");
                    }}
                    className="inline-flex items-center gap-1 mt-2 px-3 py-1.5 bg-[#1790d7] text-white text-sm font-medium rounded-lg hover:bg-[#1277b8] transition-colors"
                  >
                    Track Shipment →
                  </button>
                )}
              </div>
            ))
          ) : (
            <div className="p-4 bg-blue-50 rounded-2xl border border-blue-100">
              {order.tracking_carrier && (
                <p className="text-sm text-gray-600 mb-1">Courier: <span className="font-medium">{order.tracking_carrier}</span></p>
              )}
              {order.tracking_number && (
                <p className="text-sm font-semibold text-gray-900 mb-1">
                  Tracking ID: <span className="font-mono text-[#1790d7]">{order.tracking_number}</span>
                </p>
              )}
              {order.tracking_number && (
                <button
                  type="button"
                  onClick={() => {
                    openCourierTracking({ tracking_number: order.tracking_number, tracking_url: order.tracking_url, carrier: order.tracking_carrier });
                    showSuccess("Tracking ID copied. Paste it on the courier tracking page.");
                  }}
                  className="inline-flex items-center gap-1 mt-2 px-3 py-1.5 bg-[#1790d7] text-white text-sm font-medium rounded-lg hover:bg-[#1277b8] transition-colors"
                >
                  Track Shipment →
                </button>
              )}
            </div>
          )}
        </div>
      )}

      <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden divide-y">
        {order.items?.filter((i) => parseFloat(i.price) > 0).map((i) => (
          <div key={i.id} className="p-6 flex gap-4 flex-wrap">
            <Link href={i.product?.slug ? `/product/${i.product.slug}` : "/shop"} target={i.product?.slug ? "_blank" : undefined} rel={i.product?.slug ? "noopener noreferrer" : undefined} className="flex-shrink-0">
              <img
                src={
                  i.image_url
                    ? (i.image_url.startsWith("http") ? i.image_url : `${getBackendBaseUrl()}${i.image_url.startsWith("/") ? "" : "/"}${i.image_url}`)
                    : "/assets/sample-image.webp"
                }
                alt={i.product_name}
                className="w-20 h-20 object-cover rounded-lg bg-gray-100"
              />
            </Link>
            <div className="flex-1 min-w-0">
              <Link
                href={i.product?.slug ? `/product/${i.product.slug}` : "/shop"}
                target={i.product?.slug ? "_blank" : undefined}
                rel={i.product?.slug ? "noopener noreferrer" : undefined}
                className="font-medium text-gray-900 hover:text-[#1790d7]"
              >
                {i.product_name}
              </Link>
              {i.store && (
                <Link
                  href={`/seller/${i.store.slug}`}
                  className="flex items-center gap-1 text-sm text-gray-500 hover:text-[#1790d7] mt-1"
                >
                  <Store className="w-4 h-4" />
                  {i.store.name}
                </Link>
              )}
              <p className="text-sm text-gray-500 mt-1">
                Qty: {i.quantity} × {formatPrice(parseFloat(i.price))}
              </p>
              {i.options?.variant_attributes && typeof i.options.variant_attributes === "object" && Object.keys(i.options.variant_attributes).length > 0 && (
                <p className="text-xs text-gray-600 mt-0.5">
                  Variant: {Object.entries(i.options.variant_attributes).map(([k, v]) => `${k}: ${v}`).join(", ")}
                </p>
              )}
            </div>
            <div className="flex flex-col items-end justify-between flex-shrink-0 gap-2">
              <p className="font-semibold text-[#1790d7]">
                {formatPrice(i.quantity * parseFloat(i.price))}
              </p>
              <span
                className={`px-2 py-1 rounded-lg text-xs font-medium capitalize ${
                  ["completed", "delivered"].includes(i.seller_portion_status || "pending") ? "bg-emerald-100 text-emerald-700" :
                  (i.seller_portion_status === "cancelled" || i.seller_portion_status === "refunded") ? "bg-red-100 text-red-700" : "bg-amber-100 text-amber-700"
                }`}
              >
                Seller: {(i.seller_portion_status || "pending").replace(/_/g, " ")}
              </span>
            </div>
          </div>
        ))}
      </div>

      {/* Issue 13: Coupon details and discount on order detail */}
      <div className="mt-6 p-6 bg-gray-50 rounded-2xl space-y-2">
        {order.subtotal != null && (
          <div className="flex justify-between text-sm text-gray-600">
            <span>Order Price</span>
            <span>{formatPrice(order.subtotal)}</span>
          </div>
        )}
        {order.shipping_cost != null && parseFloat(order.shipping_cost) > 0 && (
          <div className="flex justify-between text-sm text-gray-600">
            <span>Shipping</span>
            <span>{formatPrice(order.shipping_cost)}</span>
          </div>
        )}
        {(order.coupon_code || (order.coupon && order.coupon.code) || (order.discount_amount != null && parseFloat(order.discount_amount) > 0)) && (
          <div className="flex justify-between text-sm text-emerald-600">
            <span>Coupon discount{order.coupon_code ? ` (${order.coupon_code})` : order.coupon?.code ? ` (${order.coupon.code})` : ""}</span>
            <span>−{formatPrice(order.discount_amount || 0)}</span>
          </div>
        )}
        {parseFloat(order.marketplace_fee || 0) > 0 && (
          <div className="flex justify-between text-sm text-gray-600">
            <span>
              Marketplace Fee
              {order.marketplace_fee_type === "percentage" && order.marketplace_fee_rate != null
                ? ` (${order.marketplace_fee_rate}%)`
                : ""}
            </span>
            <span>{formatPrice(order.marketplace_fee)}</span>
          </div>
        )}
        {parseFloat(order.online_transaction_fee || 0) > 0 && (
          <div className="flex justify-between text-sm text-gray-600">
            <span>
              Online Transaction Fee
              {order.online_transaction_fee_type === "percentage" && order.online_transaction_fee_rate != null
                ? ` (${order.online_transaction_fee_rate}%)`
                : ""}
            </span>
            <span>{formatPrice(order.online_transaction_fee)}</span>
          </div>
        )}
        <div className="flex justify-between text-lg font-semibold pt-2 border-t border-gray-200">
          <span>Total Amount</span>
          <span className="text-[#1790d7]">{formatPrice(order.total)}</span>
        </div>
        <p className="text-sm text-gray-500 mt-2">
          Payment: {order.payment_method || "—"} • {order.payment_status || "—"}
        </p>
        {(parseFloat(order.online_amount || 0) > 0 || parseFloat(order.cod_amount || 0) > 0) && (
          <div className="mt-3 pt-3 border-t border-gray-200 space-y-1 text-sm">
            {parseFloat(order.online_amount || 0) > 0 && (
              <div className="flex justify-between text-gray-600">
                <span>Paid online{order.partial_payment_percent ? ` (${order.partial_payment_percent}%)` : ""}</span>
                <span>{formatPrice(order.online_amount)}</span>
              </div>
            )}
            {parseFloat(order.cod_amount || 0) > 0 && (
              <div className="flex justify-between text-amber-700">
                <span>Due on delivery</span>
                <span className="font-medium">{formatPrice(order.cod_amount)}</span>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Order timeline */}
      {order.timeline && order.timeline.length > 0 && (
        <div className="mt-6 p-6 border border-gray-100 rounded-2xl">
          <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
            <Clock className="w-5 h-5 text-gray-500" />
            Order timeline
          </h3>
          <ul className="space-y-2">
            {order.timeline.map((t) => (
              <li key={t.id} className="flex items-start gap-3 text-sm">
                <span className="text-gray-500 shrink-0">
                  {t.created_at ? new Date(t.created_at).toLocaleString() : ""}
                </span>
                <span className="font-medium capitalize text-gray-800">{t.status?.replace(/_/g, " ")}</span>
                {t.note && <span className="text-gray-600">— {t.note}</span>}
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Update notes (when order can still be updated) */}
      {canUpdateNotes && (
        <div className="mt-6 p-6 border border-gray-100 rounded-2xl">
          <h3 className="font-semibold text-gray-900 mb-2">Order notes</h3>
          {editingNotes ? (
            <div className="space-y-2">
              <textarea
                value={customerNotes}
                onChange={(e) => setCustomerNotes(e.target.value)}
                rows={2}
                className="w-full px-4 py-2 border border-gray-200 rounded-xl"
                placeholder="Special instructions for this order..."
              />
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={saveNotes}
                  disabled={notesSaving}
                  className="px-4 py-2 bg-[#1790d7] text-white rounded-xl text-sm font-medium hover:bg-[#1277b8] disabled:opacity-50"
                >
                  {notesSaving ? "Saving..." : "Save"}
                </button>
                <button
                  type="button"
                  onClick={() => { setEditingNotes(false); setCustomerNotes(order.customer_notes ?? ""); }}
                  className="px-4 py-2 border border-gray-200 rounded-xl text-sm font-medium hover:bg-gray-50"
                >
                  Cancel
                </button>
              </div>
            </div>
          ) : (
            <p className="text-gray-600 text-sm">
              {order.customer_notes ? order.customer_notes : "No notes."}
              <button type="button" onClick={() => setEditingNotes(true)} className="ml-2 text-[#1790d7] hover:underline">
                Edit
              </button>
            </p>
          )}
        </div>
      )}

      {/* Issue 19: Clear dispute, return & refund flow; pending orders cannot be disputed */}
      {order.status !== "cancelled" && order.status !== "pending" && (
        <div className="mt-6 p-4 bg-gray-50 rounded-2xl border border-gray-100">
          <h3 className="font-semibold text-gray-900 mb-2">Disputes & returns</h3>
          <p className="text-sm text-gray-600 mb-2">
            <strong>Pending orders:</strong> You cannot open a dispute on unpaid or pending orders. Use &quot;Cancel order&quot; above to cancel before payment.
          </p>
          {(order.status === "paid" || order.status === "processing" || order.status === "shipped") && (
            <p className="text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-2">
              <strong>Return/refund:</strong> Available only after your order has been delivered. Until then, no payment has been completed (e.g. for COD); use &quot;Cancel order&quot; if you no longer want it.
            </p>
          )}
          <p className="text-sm text-gray-600 mb-2">
            <strong>Refund (no escalation):</strong> Once your order is delivered, you can request a return or refund from this page. Support will process your request.
          </p>
          <p className="text-sm text-gray-600 mb-2">
            <strong>Dispute (escalation):</strong> For issues like wrong item, quality, or seller not responding. A dispute applies to the <strong>entire order</strong>. If your order has items from multiple sellers, admin will handle refunds per seller after reviewing the dispute.
          </p>
          <p className="text-sm text-amber-700 mb-3">
            Return/refund flow: Request return or refund below → support reviews → you may be asked to ship items back → refund is processed per seller when approved.
          </p>
          <Link
            href={`/customer/disputes/new?order_id=${order.id}`}
            className="inline-flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-xl text-gray-700 hover:bg-gray-50 font-medium"
          >
            <AlertCircle className="w-4 h-4" />
            Open Dispute
          </Link>
        </div>
      )}

      {/* Product reviews — only after order is completed */}
      {canReview && reviewableItems.length > 0 && (
        <div className="mt-6 p-6 border border-gray-100 rounded-2xl">
          <h3 className="font-semibold text-gray-900 mb-2 flex items-center gap-2">
            <Star className="w-5 h-5 text-amber-500" />
            Write a product review
          </h3>
          <p className="text-sm text-gray-500 mb-4">
            Rate and review one or more products from this order. Reviews appear on the product page after admin approval.
          </p>
          {!showReviewForm ? (
            <button
              type="button"
              onClick={() => {
                selectAllProducts();
                setShowReviewForm(true);
              }}
              className="px-4 py-2 bg-[#1790d7] text-white rounded-xl text-sm font-medium hover:bg-[#1277b8]"
            >
              Add review
            </button>
          ) : (
            <form onSubmit={submitReview} className="space-y-4">
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="block text-sm font-medium text-gray-700">Products to review</label>
                  <button type="button" onClick={selectAllProducts} className="text-xs text-[#1790d7] hover:underline">
                    Select all
                  </button>
                </div>
                <div className="space-y-2 max-h-48 overflow-y-auto border border-gray-100 rounded-xl p-3">
                  {reviewableItems.map((i) => (
                    <label key={i.id} className="flex items-center gap-3 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={selectedProductIds.includes(i.product_id)}
                        onChange={() => toggleProduct(i.product_id)}
                        className="rounded border-gray-300 text-[#1790d7]"
                      />
                      <span className="text-sm text-gray-800">{i.product_name}</span>
                    </label>
                  ))}
                </div>
                <p className="text-xs text-gray-500 mt-1">Same rating and review text will apply to all selected products.</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Rating</label>
                <div className="flex gap-1">
                  {[1, 2, 3, 4, 5].map((i) => (
                    <button key={i} type="button" onClick={() => setReviewRating(i)} className="p-1">
                      <Star className={`w-8 h-8 ${i <= reviewRating ? "text-amber-400 fill-amber-400" : "text-gray-300"}`} />
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Title (optional)</label>
                <input
                  type="text"
                  value={reviewTitle}
                  onChange={(e) => setReviewTitle(e.target.value)}
                  className="w-full px-4 py-2 border border-gray-200 rounded-xl text-sm"
                  placeholder="Summarize your experience"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Review</label>
                <textarea
                  value={reviewBody}
                  onChange={(e) => setReviewBody(e.target.value)}
                  rows={4}
                  className="w-full px-4 py-2 border border-gray-200 rounded-xl text-sm"
                  placeholder="Share details about quality, shipping, and overall experience"
                  required
                />
              </div>
              <div className="flex gap-2">
                <button
                  type="submit"
                  disabled={reviewSubmitting}
                  className="px-4 py-2 bg-[#1790d7] text-white rounded-xl text-sm font-medium disabled:opacity-50"
                >
                  {reviewSubmitting ? "Submitting..." : "Submit review"}
                </button>
                <button
                  type="button"
                  onClick={() => setShowReviewForm(false)}
                  className="px-4 py-2 text-gray-600 text-sm"
                >
                  Cancel
                </button>
              </div>
            </form>
          )}
        </div>
      )}
      {canReview && reviewableItems.length === 0 && reviewedProductIds.length > 0 && (
        <div className="mt-6 p-4 bg-emerald-50 border border-emerald-100 rounded-2xl text-sm text-emerald-800">
          Thanks — your review for this order was submitted and will show on product pages after admin approval.
        </div>
      )}

      {/* Request return / Refund – only after order is delivered (and payment completed for COD) */}
      {(order.status === "delivered" || order.status === "completed" || ["delivered", "completed"].includes(order.complete_order_status)) && order.status !== "refunded" && (
        <div className="mt-6 p-6 border border-gray-100 rounded-2xl">
          <h3 className="font-semibold text-gray-900 mb-2 flex items-center gap-2">
            <RotateCcw className="w-5 h-5 text-amber-600" />
            Request return or refund
          </h3>
          {order.has_open_dispute && (
            <p className="text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-3">
              You have an open dispute for this order. Refunds may be handled through the dispute resolution.
            </p>
          )}
          {order.has_pending_refund && (
            <p className="text-sm text-blue-700 bg-blue-50 border border-blue-200 rounded-lg px-3 py-2 mb-3">
              You already have a pending refund request. Support will process it.
            </p>
          )}
          <p className="text-sm text-gray-500 mb-3">Submit a return or refund request. You can request full or partial amount.</p>
          <div className="flex flex-wrap gap-2 items-end">
            <div className="flex-1 min-w-[120px]">
              <label className="block text-xs font-medium text-gray-500 mb-1">Amount</label>
              <input
                type="number"
                step="0.01"
                min="0"
                placeholder={String(parseFloat(order.total) || "")}
                value={refundAmount}
                onChange={(e) => setRefundAmount(e.target.value)}
                className="w-full px-4 py-2 border border-gray-200 rounded-xl"
              />
            </div>
            <button
              onClick={async () => {
                const amount = refundAmount ? parseFloat(refundAmount) : parseFloat(order.total);
                if (!amount || amount <= 0) {
                  showError?.("Enter a valid amount or leave blank for full refund");
                  return;
                }
                setRefundLoading(true);
                try {
                  await refundApi.request({
                    order_id: order.id,
                    amount,
                    reason: "Customer return/refund request",
                  });
                  setRefundAmount("");
                  setOrder((o) => o && { ...o, refund_requested: true });
                  showSuccess?.("Refund request submitted");
                } catch (e) {
                  showError?.(e?.data?.message || e?.message || "Failed to submit request");
                } finally {
                  setRefundLoading(false);
                }
              }}
              disabled={refundLoading}
              className="px-4 py-2 bg-amber-500 text-white rounded-xl hover:bg-amber-600 disabled:opacity-50 font-medium"
            >
              {refundLoading ? "Submitting..." : "Request return / refund"}
            </button>
          </div>
        </div>
      )}

      {order.shipping_address && (
        <div className="mt-6 p-6 border border-gray-100 rounded-2xl">
          <h3 className="font-semibold text-gray-900 mb-2">Shipping Address</h3>
          <p className="text-gray-600">
            {order.shipping_address.first_name} {order.shipping_address.last_name}
            <br />
            {order.shipping_address.address_line_1}
            {order.shipping_address.address_line_2 && `, ${order.shipping_address.address_line_2}`}
            <br />
            {order.shipping_address.city}
            {order.shipping_address.state && `, ${order.shipping_address.state}`}
            {order.shipping_address.country}
            <br />
            {order.shipping_address.phone}
          </p>
        </div>
      )}
    </div>
  );
}
