import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Badge, Btn, cn } from "@/pages/app/components/ui";
import { merchantOrders, orderSteps, type MerchantOrder } from "@/mocks/dshnBusiness";

const SHIPPING_STEPS = ["تم الشحن", "جاري التوصيل"];

function OptionsMenu({ onDispute }: { onDispute: () => void }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="relative shrink-0">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-label="خيارات"
        className="w-10 h-10 rounded-full flex items-center justify-center text-foreground-950 hover:bg-background-200 cursor-pointer"
      >
        <i className="ri-more-2-fill text-[21px] leading-none" />
      </button>
      {open && (
        <>
          <button
            type="button"
            aria-label="إغلاق"
            onClick={() => setOpen(false)}
            className="absolute inset-0 -z-10"
          />
          <div className="absolute top-11 left-0 w-[180px] rounded-[16px] bg-background-100 border border-background-200 overflow-hidden z-40 animate-fade-in">
            <button
              type="button"
              onClick={() => {
                setOpen(false);
                onDispute();
              }}
              className="w-full flex items-center gap-2.5 px-4 py-3 text-right text-[13px] text-danger-600 hover:bg-danger-50 cursor-pointer"
            >
              <i className="ri-flag-2-line text-[17px] leading-none" />
              فتح نزاع
            </button>
          </div>
        </>
      )}
    </div>
  );
}

function ItemRow({ item }: { item: MerchantOrder["items"][number] }) {
  return (
    <div className="flex items-center gap-3 py-3">
      <div className="w-12 h-12 rounded-[12px] overflow-hidden bg-background-200 shrink-0">
        <img src={item.image} alt={item.name} className="w-full h-full object-cover object-top" />
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-[12.5px] font-medium text-foreground-950 leading-snug line-clamp-2">{item.name}</p>
        <p className="text-[11px] text-foreground-600 mt-0.5">الكمية: {item.qty}</p>
      </div>
      <span className="shrink-0 whitespace-nowrap text-[12.5px] font-semibold text-foreground-950">
        {item.price.toLocaleString("en-US")} ر.س
      </span>
    </div>
  );
}

export default function BizOrder({ variant = "detail" }: { variant?: "detail" | "shipped" | "fromNegotiation" }) {
  const { goBack, params, navigate } = useApp();
  const fallback =
    variant === "shipped"
      ? merchantOrders.find((o) => o.status === "current") ?? merchantOrders[0]
      : variant === "fromNegotiation"
        ? merchantOrders.find((o) => o.id === "boo7") ?? merchantOrders.find((o) => o.status === "new") ?? merchantOrders[0]
        : merchantOrders.find((o) => o.status === "new") ?? merchantOrders[0];
  const order = merchantOrders.find((o) => o.number === params.orderId) ?? fallback;

  const [shipStep, setShipStep] = useState(0);

  const isShipped = variant === "shipped";
  const canConfirmShip = !isShipped && order.status === "new";

  return (
    <div className="min-h-full pb-28 bg-background-50">
      <BackHeader
        title={isShipped ? "الطلب - الشحن" : "تفاصيل الطلب"}
        subtitle={`طلب #${order.number}`}
        onBack={goBack}
        action={<OptionsMenu onDispute={() => navigate("bizDispute", { orderId: order.number })} />}
      />

      <div className="px-4 py-5 space-y-4">
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4 flex items-center justify-between gap-3">
          <div>
            <p className="text-[11px] text-foreground-600">حالة الطلب</p>
            <p className="text-[15px] font-bold text-foreground-950 mt-1">
              {isShipped ? SHIPPING_STEPS[shipStep] : order.statusLabel}
            </p>
          </div>
          <Badge tone={isShipped ? "info" : order.statusTone}>
            {isShipped ? SHIPPING_STEPS[shipStep] : order.statusLabel}
          </Badge>
        </div>

        {isShipped && (
          <div className="rounded-[18px] bg-background-100 border border-background-200 p-4">
            <p className="text-[13px] font-semibold text-foreground-950 mb-3">مراحل الطلب</p>
            <div className="flex items-center gap-2">
              {orderSteps.map((s, i) => {
                const activeIndex = shipStep + 1; // paid=0, shipped=1, delivering=2
                return (
                  <div key={s.key} className="flex items-center flex-1 last:flex-none">
                    <div className="flex flex-col items-center gap-1.5 min-w-0">
                      <span
                        className={cn(
                          "w-3 h-3 rounded-full shrink-0",
                          i <= activeIndex ? "bg-accent-500" : "bg-background-300",
                        )}
                      />
                      <span
                        className={cn(
                          "text-[9px] text-center leading-tight",
                          i === activeIndex ? "font-bold text-foreground-950" : "text-foreground-500",
                        )}
                      >
                        {s.label}
                      </span>
                    </div>
                    {i < orderSteps.length - 1 && (
                      <span className={cn("flex-1 h-px mt-[-14px]", i < activeIndex ? "bg-accent-500" : "bg-background-300")} />
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}

        <div className="rounded-[18px] bg-background-100 border border-background-200 p-4">
          <p className="text-[13px] font-semibold text-foreground-950 mb-1">المنتجات والكميات</p>
          <div className="divide-y divide-background-200">
            {order.items.map((it) => (
              <ItemRow key={it.name} item={it} />
            ))}
          </div>
        </div>

        <div className="rounded-[18px] bg-background-100 border border-background-200 p-4">
          <p className="text-[13px] font-semibold text-foreground-950 mb-3">بيانات العميل والعنوان</p>
          <div className="space-y-2.5">
            <div className="flex items-center justify-between gap-3">
              <span className="text-[12px] text-foreground-600">الاسم</span>
              <span className="text-[12.5px] font-medium text-foreground-950">{order.customer}</span>
            </div>
            <div className="flex items-center justify-between gap-3">
              <span className="text-[12px] text-foreground-600">الجوال</span>
              <span className="text-[12.5px] font-medium text-foreground-950" dir="ltr">{order.phone}</span>
            </div>
            <div className="flex items-start justify-between gap-3">
              <span className="text-[12px] text-foreground-600 shrink-0">العنوان</span>
              <span className="text-[12.5px] font-medium text-foreground-950 text-left leading-relaxed">
                {order.city} — {order.address}
              </span>
            </div>
          </div>
        </div>

        <div className="rounded-[18px] bg-background-100 border border-background-200 p-4">
          <p className="text-[13px] font-semibold text-foreground-950 mb-3">الشحن</p>
          <div className="space-y-2.5">
            <div className="flex items-center justify-between gap-3">
              <span className="text-[12px] text-foreground-600">شركة الشحن</span>
              <span className="text-[12.5px] font-medium text-foreground-950">{order.shippingCompany}</span>
            </div>
            <div className="flex items-center justify-between gap-3">
              <span className="text-[12px] text-foreground-600">تكلفة الشحن</span>
              <span className="text-[12.5px] font-bold text-foreground-950">{order.shipping.toLocaleString("en-US")} ر.س</span>
            </div>
            <div className="h-px bg-background-200" />
            <div className="flex items-center justify-between gap-3">
              <span className="text-[12.5px] font-semibold text-foreground-900">إجمالي الطلب</span>
              <span className="text-[15px] font-bold text-foreground-950">{order.total.toLocaleString("en-US")} ر.س</span>
            </div>
          </div>
        </div>
      </div>

      <div className="sticky bottom-0 z-30 px-4 py-4 bg-background-50 border-t border-background-200/70">
        {canConfirmShip ? (
          <Btn full onClick={() => navigate("bizOrderShipped", { orderId: order.number })}>
            <i className="ri-truck-line text-[18px] leading-none" />
            تأكيد الشحن
          </Btn>
        ) : isShipped ? (
          <Btn full disabled={shipStep >= SHIPPING_STEPS.length - 1} onClick={() => setShipStep((s) => s + 1)}>
            {shipStep >= SHIPPING_STEPS.length - 1 ? "تم التوصيل" : "تحديث الحالة إلى «جاري التوصيل»"}
          </Btn>
        ) : (
          <div className="h-[52px] rounded-[14px] bg-background-100 border border-background-200 flex items-center justify-center gap-2 text-[13.5px] font-medium text-foreground-600">
            <i className="ri-information-line text-[17px] leading-none" />
            لا تتوفر إجراءات لهذا الطلب حاليًا
          </div>
        )}
      </div>
    </div>
  );
}