import { useState } from "react";
import { businesses } from "@/mocks/dshn";
import { orders, shipmentSteps } from "@/mocks/dshnCommerce";
import { useWeb } from "../WebContext";
import { Container, WBtn, WCard, StatusPill, cn, fmt } from "../WebUI";
import ProgressTracker from "@/pages/app/components/ProgressTracker";

export default function OrderDetails() {
  const { t, params, goBack, navigate } = useWeb();
  const order = orders.find((o) => o.id === params.orderId) ?? orders[0];
  const biz = businesses.find((b) => b.id === order.businessId);
  const [menu, setMenu] = useState(false);

  const canConfirm = order.currentStep === 2;

  return (
    <div className="relative animate-fade-in">
      <Container className="py-8">
        <button type="button" onClick={goBack} className="inline-flex items-center gap-2 text-[13px] font-medium text-foreground-600 hover:text-foreground-950 cursor-pointer mb-5">
          <i className="ri-arrow-right-line text-[17px] leading-none" />
          رجوع
        </button>

        <div className="flex items-center justify-between gap-4 flex-wrap mb-6">
          <div>
            <h1 className="text-[26px] md:text-[30px] font-bold text-foreground-950 font-heading">طلب #{order.number}</h1>
            <p className="text-[13.5px] text-foreground-600 mt-1">{biz?.name} • {order.shippingCompany}</p>
          </div>
          <div className="flex items-center gap-3">
            <StatusPill tone={order.statusTone}>{order.statusLabel}</StatusPill>
            <div className="relative">
              <button type="button" onClick={() => setMenu((m) => !m)} className="w-10 h-10 rounded-full border border-background-200 flex items-center justify-center hover:bg-background-200 cursor-pointer">
                <i className="ri-more-2-fill text-[18px] leading-none" />
              </button>
              {menu && (
                <div className="absolute end-0 top-[calc(100%+6px)] w-44 bg-background-100 border border-background-200 rounded-[14px] p-1.5 z-20">
                  <button
                    type="button"
                    onClick={() => { setMenu(false); navigate("dispute", { orderId: order.number }); }}
                    className="w-full h-9 px-3 rounded-[10px] flex items-center gap-2 text-[13px] font-medium text-danger-600 hover:bg-danger-50 cursor-pointer"
                  >
                    <i className="ri-alert-line text-[16px] leading-none" />
                    {t("openDispute")}
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
          <div className="lg:col-span-2 space-y-6">
            <WCard className="p-6">
              <h2 className="text-[16px] font-bold text-foreground-950 mb-6">تتبع الطلب</h2>
              <ProgressTracker steps={shipmentSteps} current={order.currentStep} />
              <p className="text-[12px] text-foreground-500 mt-5">
                تُحدَّث حالة الطلب يدويًا من قبل المنشأة — لا يوجد تتبع مباشر للموقع.
              </p>
            </WCard>

            <WCard className="p-5">
              <h2 className="text-[16px] font-bold text-foreground-950 mb-4">المنتجات</h2>
              <div className="divide-y divide-background-200">
                {order.items.map((i) => (
                  <div key={i.productId} className="flex items-center gap-4 py-3.5">
                    <div className="w-14 h-14 rounded-[12px] overflow-hidden bg-background-200 shrink-0">
                      <img src={i.image} alt={i.name} className="w-full h-full object-cover object-top" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-[13.5px] font-semibold text-foreground-950 line-clamp-1">{i.name}</p>
                      <p className="text-[12px] text-foreground-600 mt-0.5">{t("quantity")}: {i.qty}</p>
                    </div>
                    <span className="text-[14px] font-bold text-foreground-900">{fmt(i.price * i.qty)} ر.س</span>
                  </div>
                ))}
              </div>
            </WCard>
          </div>

          <div className="">
            <WCard className="p-6">
              <h3 className="text-[16px] font-bold text-foreground-950 mb-4">ملخص الدفع</h3>
              <div className="space-y-2.5 text-[13.5px]">
                <Row label={t("shippingCompany")} value={order.shippingCompany} />
                <Row label={t("subtotal")} value={`${fmt(order.items.reduce((s, i) => s + i.price * i.qty, 0))} ر.س`} />
                <Row label={t("shipping")} value={`${fmt(order.shipping)} ر.س`} />
                <Row label={t("discount")} value={`- ${fmt(order.discount)} ر.س`} />
                <Row label={t("tax")} value={`${fmt(order.tax)} ر.س`} />
                <div className="h-px bg-background-200 my-2" />
                <div className="flex items-center justify-between">
                  <span className="text-[15px] font-bold text-foreground-950">الإجمالي المدفوع</span>
                  <span className="text-[20px] font-bold text-foreground-950">{fmt(order.total)} ر.س</span>
                </div>
              </div>

              {canConfirm ? (
                <WBtn full className="w-full mt-6" icon="ri-checkbox-circle-line">تأكيد استلام الطلب</WBtn>
              ) : canConfirm === false && order.currentStep >= 3 ? (
                <p className="text-[12.5px] text-accent-700 mt-5 flex items-center gap-1.5"><i className="ri-checkbox-circle-line text-[15px] leading-none" />تم تأكيد الاستلام</p>
              ) : (
                <p className="text-[12.5px] text-foreground-500 mt-5">زر تأكيد الاستلام يظهر عند وصول الطلب لحالة «جاري التوصيل».</p>
              )}
              {order.disputed && <StatusPill tone="danger" className="mt-3">متنازع عليه</StatusPill>}
            </WCard>
          </div>
        </div>
      </Container>
    </div>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="text-foreground-600">{label}</span>
      <span className={cn("font-semibold text-foreground-950 truncate")}>{value}</span>
    </div>
  );
}