import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/use-auth";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import { ArrowLeft, Printer, CheckCircle2, Share2, FileDown, History, XCircle, Undo2, MessageCircle, Pencil, Wallet } from "lucide-react";
import { RefundDialog } from "@/components/sales/RefundDialog";
import { toast } from "sonner";
import { useState } from "react";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { SaleStatusDropdown } from "@/components/sales/SaleStatusDropdown";
import { SaleStatusTimeline } from "@/components/sales/SaleStatusTimeline";
import { statusLabel, nextStatuses, type SaleStatus } from "@/components/sales/sale-status";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export const Route = createFileRoute("/_authenticated/sales-orders/$orderId")({
  head: () => ({
    meta: [{ title: "Sales Order বিস্তারিত — Niyamah ERP" }],
  }),
  component: SalesOrderDetailPage,
});

function PaymentBadge({ status, isBn }: { status: string; isBn: boolean }) {
  const map: Record<string, { label: string; cls: string }> = {
    paid: { label: "PAID", cls: "bg-green-500/15 text-green-700 dark:text-green-400 border-green-500/30" },
    due: { label: "DUE", cls: "bg-red-500/15 text-red-700 dark:text-red-400 border-red-500/30" },
    partial: { label: "PARTIAL PAID", cls: "bg-yellow-500/15 text-yellow-700 dark:text-yellow-400 border-yellow-500/30" },
  };
  const s = map[status] || map.due;
  return (
    <span className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-bold tracking-wide ${s.cls}`}>
      {s.label}
    </span>
  );
}

function SalesOrderDetailPage() {
  const { orderId } = Route.useParams();
  const { lang } = useLanguage();
  const { user } = useAuth();
  const isBn = lang === "bn";
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ["sales-order", orderId],
    queryFn: async () => {
      const { data: order, error } = await supabase
        .from("sales_orders" as any)
        .select("*, customers(name, mobile, address), branches(name)")
        .eq("id", orderId)
        .single();
      if (error) throw error;
      const { data: items } = await supabase
        .from("sales_order_items" as any)
        .select("*, products(name, sku)")
        .eq("sales_order_id", orderId);
      const { data: logs } = await supabase
        .from("sales_order_status_log" as any)
        .select("*")
        .eq("sales_order_id", orderId)
        .order("created_at", { ascending: false });
      return { order, items: (items as any[]) || [], logs: (logs as any[]) || [] };
    },
  });

  const { data: footer } = useQuery({
    queryKey: ["invoice-footer-settings"],
    queryFn: async () => {
      const { data } = await supabase
        .from("business_settings")
        .select("setting_key, setting_value")
        .in("setting_key", ["invoice_footer_terms", "invoice_footer_thanks", "company_logo_url"]);
      const map = new Map((data || []).map((s: any) => [s.setting_key, s.setting_value]));
      return {
        terms: (map.get("invoice_footer_terms") as string) || "",
        thanks: (map.get("invoice_footer_thanks") as string) || "",
        logoUrl: (map.get("company_logo_url") as string) || "/niyamah-logo.jpg",
      };
    },
  });

  // Realtime: refetch on any change to this sales order so PAID/DUE/PARTIAL updates instantly
  useEffect(() => {
    const ch = supabase
      .channel(`so-${orderId}`)
      .on("postgres_changes", { event: "*", schema: "public", table: "sales_orders", filter: `id=eq.${orderId}` },
        () => qc.invalidateQueries({ queryKey: ["sales-order", orderId] }))
      .on("postgres_changes", { event: "INSERT", schema: "public", table: "sales_order_status_log", filter: `sales_order_id=eq.${orderId}` },
        () => qc.invalidateQueries({ queryKey: ["sales-order", orderId] }))
      .subscribe();
    return () => { supabase.removeChannel(ch); };
  }, [orderId, qc]);

  const approveMutation = useMutation({
    mutationFn: async () => {
      const { error } = await supabase
        .from("sales_orders" as any)
        .update({ bill_status: "final", approved_at: new Date().toISOString(), approved_by: user?.id ?? null })
        .eq("id", orderId);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "Invoice ফাইনাল অনুমোদিত হয়েছে" : "Invoice finalized");
      qc.invalidateQueries({ queryKey: ["sales-order", orderId] });
    },
    onError: (e: any) => toast.error(e.message),
  });

  const statusMutation = useMutation({
    mutationFn: async (payload: { status: SaleStatus; reason?: string }) => {
      const update: Record<string, unknown> = { status: payload.status };
      if (payload.status === "cancelled") update.cancelled_reason = payload.reason || "";
      const { error } = await supabase.from("sales_orders" as any).update(update).eq("id", orderId);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "স্ট্যাটাস আপডেট হয়েছে" : "Status updated");
      qc.invalidateQueries({ queryKey: ["sales-order", orderId] });
      qc.invalidateQueries({ queryKey: ["sales-orders"] });
    },
    onError: (e: any) => toast.error(e.message),
  });

  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState("");
  const [returnOpen, setReturnOpen] = useState(false);
  const [refundOpen, setRefundOpen] = useState(false);

  // Refund history for this order (matched by note containing "Order: <orderNo>")
  const orderRow: any = data?.order;
  const { data: refunds = [] } = useQuery({
    queryKey: ["order-refunds", orderId],
    enabled: !!orderRow?.customer_id && !!orderRow?.order_no,
    queryFn: async () => {
      const { data: rows } = await supabase
        .from("refunds")
        .select("*")
        .eq("customer_id", orderRow.customer_id)
        .ilike("note", `%${orderRow.order_no}%`)
        .order("created_at", { ascending: false });
      return (rows as any[]) || [];
    },
  });

  if (isLoading) return <PageLayout><div className="p-8 text-center text-muted-foreground">Loading...</div></PageLayout>;
  if (!data?.order) return <PageLayout><div className="p-8 text-center">Not found</div></PageLayout>;

  const o = data.order as any;
  const isRough = o.bill_status !== "final";
  const allowed = nextStatuses(o.status as SaleStatus);
  const canCancel = allowed.includes("cancelled");
  const canReturn = allowed.includes("returned");
  const canRefund = o.status === "returned";
  const totalRefunded = refunds.reduce((s: number, r: any) => s + Number(r.amount || 0), 0);
  const refundableMax = Math.max(0, Number(o.paid_amount || 0) - totalRefunded);

  const handleShare = async () => {
    const url = window.location.href;
    const title = `${isRough ? "Rough Bill" : "Invoice"} ${o.order_no}`;
    try {
      if (navigator.share) {
        await navigator.share({ title, url });
      } else {
        await navigator.clipboard.writeText(url);
        toast.success(isBn ? "লিংক কপি হয়েছে" : "Link copied");
      }
    } catch {/* user cancelled */}
  };

  const handleWhatsApp = () => {
    const url = window.location.href;
    const text = `${isBn ? "ইনভয়েস" : "Invoice"} ${o.order_no}\n${isBn ? "মোট" : "Total"}: ৳${Number(o.total_amount).toLocaleString()}\n${url}`;
    const mobile = (o.customers?.mobile || "").replace(/\D/g, "");
    const wa = mobile
      ? `https://wa.me/${mobile}?text=${encodeURIComponent(text)}`
      : `https://wa.me/?text=${encodeURIComponent(text)}`;
    window.open(wa, "_blank", "noopener");
  };

  const handlePDF = () => {
    const doc = new jsPDF();
    doc.setFontSize(16);
    doc.text(`${isRough ? "ROUGH BILL" : "Invoice"} - ${o.order_no}`, 14, 18);
    doc.setFontSize(10);
    doc.text(`Date: ${o.order_date}`, 14, 26);
    doc.text(`Customer: ${o.customers?.name || "Walk-in"}`, 14, 32);
    if (o.customers?.mobile) doc.text(`Mobile: ${o.customers.mobile}`, 14, 38);
    autoTable(doc, {
      startY: 44,
      head: [["Product", "Qty", "Price", "Total"]],
      body: data.items.map((it: any) => [
        it.products?.name || "",
        it.quantity,
        Number(it.price).toFixed(2),
        Number(it.total).toFixed(2),
      ]),
    });
    const finalY = (doc as any).lastAutoTable.finalY + 8;
    doc.text(`Discount: ${Number(o.discount).toFixed(2)}`, 140, finalY);
    doc.text(`Total: ${Number(o.total_amount).toFixed(2)}`, 140, finalY + 6);
    doc.text(`Paid: ${Number(o.paid_amount).toFixed(2)}`, 140, finalY + 12);
    doc.text(`Due: ${Number(o.due_amount).toFixed(2)}`, 140, finalY + 18);
    const stamp = isRough
      ? { label: "ROUGH BILL", rgb: [220, 38, 38] as const }
      : o.payment_status === "paid"
      ? { label: "PAID", rgb: [22, 163, 74] as const }
      : o.payment_status === "partial"
      ? { label: "PARTIAL PAID", rgb: [202, 138, 4] as const }
      : { label: "DUE", rgb: [220, 38, 38] as const };
    doc.setTextColor(stamp.rgb[0], stamp.rgb[1], stamp.rgb[2]);
    doc.setFontSize(48);
    doc.text(stamp.label, 105, 150, { align: "center", angle: 30 });

    // Footer single-line at bottom of page
    const footerLine = [footer?.terms, footer?.thanks].filter(Boolean).join(" — ");
    if (footerLine) {
      doc.setTextColor(0, 0, 0);
      doc.setFontSize(9);
      const pageH = doc.internal.pageSize.getHeight();
      doc.text(footerLine, 105, pageH - 8, { align: "center" });
    }

    doc.save(`${isRough ? "rough-bill" : "invoice"}-${o.order_no}.pdf`);
  };

  const stampInfo = isRough
    ? { label: "ROUGH BILL", color: "text-red-600", border: "border-red-600" }
    : o.payment_status === "paid"
    ? { label: "PAID", color: "text-green-600", border: "border-green-600" }
    : o.payment_status === "partial"
    ? { label: "PARTIAL PAID", color: "text-yellow-600", border: "border-yellow-600" }
    : { label: "DUE", color: "text-red-600", border: "border-red-600" };

  return (
    <PageLayout>
      <style>{`
        @media print {
          .no-print { display: none !important; }
          .stamp-watermark { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }
      `}</style>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-2 no-print">
        <Link to="/sales-orders" className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground">
          <ArrowLeft className="h-4 w-4" />
          {isBn ? "ফিরে যান" : "Back"}
        </Link>
        <div className="flex items-center gap-2 flex-wrap">
          {isRough && (
            <button
              onClick={() => approveMutation.mutate()}
              disabled={approveMutation.isPending}
              className="flex items-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-sm font-semibold text-white hover:bg-green-700 disabled:opacity-50"
            >
              <CheckCircle2 className="h-4 w-4" />
              {isBn ? "ফাইনাল অনুমোদন" : "Final Approve"}
            </button>
          )}
          {o.status !== "cancelled" && o.status !== "returned" && (
            <Link
              to="/sales-orders/$orderId/edit"
              params={{ orderId: o.id }}
              className="flex items-center gap-2 rounded-lg border border-blue-500/40 bg-blue-500/10 px-3 py-2 text-sm text-blue-700 dark:text-blue-400 hover:bg-blue-500/20"
            >
              <Pencil className="h-4 w-4" />
              {isBn ? "এডিট" : "Edit"}
            </Link>
          )}
          {canReturn && (
            <button
              onClick={() => setReturnOpen(true)}
              className="flex items-center gap-2 rounded-lg border border-orange-500/40 bg-orange-500/10 px-3 py-2 text-sm text-orange-700 dark:text-orange-400 hover:bg-orange-500/20"
            >
              <Undo2 className="h-4 w-4" />
              {isBn ? "রিটার্ন" : "Return"}
            </button>
          )}
          {canRefund && refundableMax > 0 && (
            <button
              onClick={() => setRefundOpen(true)}
              className="flex items-center gap-2 rounded-lg border border-purple-500/40 bg-purple-500/10 px-3 py-2 text-sm text-purple-700 dark:text-purple-400 hover:bg-purple-500/20"
            >
              <Wallet className="h-4 w-4" />
              {isBn ? "রিফান্ড" : "Refund"}
            </button>
          )}
          {canCancel && (
            <button
              onClick={() => { setCancelReason(""); setCancelOpen(true); }}
              className="flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive hover:bg-destructive/20"
            >
              <XCircle className="h-4 w-4" />
              {isBn ? "বাতিল" : "Cancel"}
            </button>
          )}
          <button onClick={handleWhatsApp} className="flex items-center gap-2 rounded-lg border border-green-500/40 bg-green-500/10 px-3 py-2 text-sm text-green-700 dark:text-green-400 hover:bg-green-500/20">
            <MessageCircle className="h-4 w-4" />
            WhatsApp
          </button>
          <button onClick={handleShare} className="flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted">
            <Share2 className="h-4 w-4" />
            {isBn ? "শেয়ার" : "Share"}
          </button>
          <button onClick={handlePDF} className="flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted">
            <FileDown className="h-4 w-4" />
            PDF
          </button>
          <button onClick={() => window.print()} className="flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted">
            <Printer className="h-4 w-4" />
            {isBn ? "প্রিন্ট" : "Print"}
          </button>
        </div>
      </div>

      <div className="mb-6 no-print">
        <SaleStatusTimeline current={o.status} logs={data.logs} />
      </div>

      <div className="relative rounded-xl border border-border bg-card p-4 sm:p-6 space-y-6 overflow-hidden">
        <div className="stamp-watermark pointer-events-none absolute inset-0 flex items-center justify-center z-10">
          <div className={`rotate-[-25deg] border-[6px] ${stampInfo.border} px-6 sm:px-10 py-2 sm:py-3 rounded-md opacity-20`}>
            <span className={`text-3xl sm:text-5xl md:text-6xl font-black tracking-widest ${stampInfo.color}`}>
              {stampInfo.label}
            </span>
          </div>
        </div>

        <div className="flex justify-between items-start flex-wrap gap-4 relative z-20">
          <div>
            <h1 className="text-2xl font-bold">{isRough ? (isBn ? "Rough Bill" : "Rough Bill") : (isBn ? "ইনভয়েস" : "Invoice")}</h1>
            <div className="text-sm text-muted-foreground font-mono mt-1">{o.order_no}</div>
          </div>
          <div className="text-right text-sm space-y-1">
            <div><span className="text-muted-foreground">{isBn ? "তারিখ:" : "Date:"}</span> {o.order_date}</div>
            {o.delivery_date && <div><span className="text-muted-foreground">{isBn ? "ডেলিভারি:" : "Delivery:"}</span> {o.delivery_date}</div>}
            <div className="flex items-center gap-2 justify-end pt-1 flex-wrap">
              <PaymentBadge status={o.payment_status || "due"} isBn={isBn} />
              <SaleStatusDropdown orderId={o.id} current={o.status} />
            </div>
          </div>
        </div>

        <div className="grid sm:grid-cols-2 gap-4 text-sm relative z-20">
          <div>
            <div className="text-xs text-muted-foreground mb-1">{isBn ? "গ্রাহক" : "Customer"}</div>
            <div className="font-medium">{o.customers?.name || (isBn ? "ওয়াক-ইন" : "Walk-in")}</div>
            {o.customers?.mobile && <div className="text-muted-foreground">{o.customers.mobile}</div>}
            {o.customers?.address && <div className="text-muted-foreground text-xs">{o.customers.address}</div>}
          </div>
          {o.branches?.name && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">{isBn ? "শাখা" : "Branch"}</div>
              <div className="font-medium">{o.branches.name}</div>
            </div>
          )}
        </div>

        <div className="overflow-x-auto relative z-20">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left">
                <th className="py-2 font-medium">{isBn ? "পণ্য" : "Product"}</th>
                <th className="py-2 font-medium text-right">{isBn ? "পরিমাণ" : "Qty"}</th>
                <th className="py-2 font-medium text-right">{isBn ? "মূল্য" : "Price"}</th>
                <th className="py-2 font-medium text-right">{isBn ? "মোট" : "Total"}</th>
              </tr>
            </thead>
            <tbody>
              {data.items.map((it: any) => (
                <tr key={it.id} className="border-b border-border/30">
                  <td className="py-2">
                    <div>{it.products?.name}</div>
                    <div className="text-xs text-muted-foreground">{it.products?.sku}</div>
                  </td>
                  <td className="py-2 text-right">{it.quantity}</td>
                  <td className="py-2 text-right">৳{Number(it.price).toLocaleString()}</td>
                  <td className="py-2 text-right font-medium">৳{Number(it.total).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="ml-auto w-full max-w-sm space-y-2 text-sm relative z-20">
          <div className="flex justify-between"><span className="text-muted-foreground">{isBn ? "ছাড়" : "Discount"}</span><span>৳{Number(o.discount).toLocaleString()}</span></div>
          <div className="flex justify-between font-semibold pt-2 border-t border-border"><span>{isBn ? "মোট" : "Total"}</span><span className="text-primary">৳{Number(o.total_amount).toLocaleString()}</span></div>
          <div className="flex justify-between"><span className="text-muted-foreground">{isBn ? "পরিশোধিত (Paid)" : "Paid"}:</span><span>৳{Number(o.paid_amount).toLocaleString()}</span></div>
          <div className="flex justify-between font-semibold"><span>{isBn ? "বকেয়া" : "Due"}</span><span className="text-orange-600">৳{Number(o.due_amount).toLocaleString()}</span></div>
        </div>

        {o.note && (
          <div className="text-sm relative z-20">
            <div className="text-xs text-muted-foreground mb-1">{isBn ? "নোট" : "Note"}</div>
            <div className="text-muted-foreground">{o.note}</div>
          </div>
        )}

        {(footer?.terms || footer?.thanks) && (
          <div className="relative z-20 pt-4 mt-4 border-t border-border text-center">
            <p className="text-xs text-foreground truncate">
              {[footer?.terms, footer?.thanks].filter(Boolean).join(" — ")}
            </p>
          </div>
        )}
      </div>

      {data.logs.length > 0 && (
        <div className="mt-6 rounded-xl border border-border bg-card p-4 no-print">
          <div className="flex items-center gap-2 mb-3">
            <History className="h-4 w-4 text-muted-foreground" />
            <h3 className="font-semibold text-sm">{isBn ? "স্ট্যাটাস ইতিহাস" : "Status History"}</h3>
          </div>
          <div className="space-y-2">
            {data.logs.map((l: any) => {
              const isStatus = l.change_type === "status" || l.change_type === "created";
              const oldText = isStatus && l.old_value ? statusLabel(l.old_value, isBn) : (l.old_value || "—");
              const newText = isStatus && l.new_value ? statusLabel(l.new_value, isBn) : (l.new_value || "—");
              return (
                <div key={l.id} className="flex items-center justify-between text-xs border-b border-border/40 last:border-0 pb-2 last:pb-0">
                  <div>
                    <span className="font-medium uppercase text-muted-foreground">{l.change_type}</span>
                    <span className="mx-2">·</span>
                    <span>{oldText} → <span className="font-semibold">{newText}</span></span>
                  </div>
                  <span className="text-muted-foreground">{new Date(l.created_at).toLocaleString()}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <Dialog open={cancelOpen} onOpenChange={setCancelOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{isBn ? "ইনভয়েস বাতিল" : "Cancel Invoice"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-2">
            <label className="text-sm text-muted-foreground">{isBn ? "কারণ (আবশ্যক)" : "Reason (required)"}</label>
            <textarea
              value={cancelReason}
              onChange={(e) => setCancelReason(e.target.value)}
              rows={3}
              className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
              placeholder={isBn ? "বাতিলের কারণ লিখুন" : "Why are you cancelling?"}
            />
          </div>
          <DialogFooter>
            <button onClick={() => setCancelOpen(false)} className="rounded-md border border-border px-3 py-2 text-sm">
              {isBn ? "বন্ধ" : "Close"}
            </button>
            <button
              disabled={!cancelReason.trim() || statusMutation.isPending}
              onClick={() => statusMutation.mutate(
                { status: "cancelled", reason: cancelReason.trim() },
                { onSuccess: () => setCancelOpen(false) }
              )}
              className="rounded-md bg-destructive px-3 py-2 text-sm text-destructive-foreground disabled:opacity-50"
            >
              {isBn ? "নিশ্চিত বাতিল" : "Confirm Cancel"}
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={returnOpen} onOpenChange={setReturnOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{isBn ? "রিটার্ন নিশ্চিত করুন" : "Confirm Return"}</AlertDialogTitle>
            <AlertDialogDescription>
              {isBn
                ? "এই ইনভয়েস রিটার্ন হিসেবে চিহ্নিত হবে এবং স্টক পুনরুদ্ধার হবে।"
                : "This invoice will be marked as returned and stock will be restored."}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{isBn ? "বাতিল" : "Cancel"}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => statusMutation.mutate(
                { status: "returned" },
                { onSuccess: () => setReturnOpen(false) }
              )}
            >
              {isBn ? "নিশ্চিত রিটার্ন" : "Confirm Return"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {refunds.length > 0 && (
        <div className="mt-6 rounded-xl border border-border bg-card p-4 no-print">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <Wallet className="h-4 w-4 text-purple-600" />
              <h3 className="font-semibold text-sm">{isBn ? "রিফান্ড ইতিহাস" : "Refund History"}</h3>
            </div>
            <div className="text-xs text-muted-foreground">
              {isBn ? "মোট রিফান্ড:" : "Total refunded:"} <span className="font-semibold text-purple-700">৳{totalRefunded.toLocaleString()}</span>
            </div>
          </div>
          <div className="space-y-2">
            {refunds.map((r: any) => (
              <div key={r.id} className="flex items-center justify-between text-xs border-b border-border/40 last:border-0 pb-2 last:pb-0">
                <div>
                  <span className="font-semibold text-purple-700">৳{Number(r.amount).toLocaleString()}</span>
                  <span className="mx-2">·</span>
                  <span className="uppercase text-muted-foreground">{r.payment_method}</span>
                  <span className="mx-2">·</span>
                  <span className={`uppercase ${r.status === "completed" ? "text-green-600" : "text-yellow-600"}`}>{r.status}</span>
                  {r.note && <div className="text-muted-foreground mt-0.5">{r.note}</div>}
                </div>
                <span className="text-muted-foreground">{new Date(r.created_at).toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <RefundDialog
        open={refundOpen}
        onOpenChange={setRefundOpen}
        orderId={o.id}
        orderNo={o.order_no}
        customerId={o.customer_id}
        maxAmount={refundableMax}
        isBn={isBn}
      />
    </PageLayout>
  );
}
