import { useState } from "react";
import { useApp } from "../AppContext";
import { businesses, shippingCompanies } from "@/mocks/dshn";
import { savedAddresses } from "@/mocks/dshnAddresses";
import { products } from "@/mocks/dshnCommerce";
import { BackHeader, Card, cn } from "../components/ui";

const CART = [
  { productId: "pr1", qty: 2 },
  { productId: "pr2", qty: 1 },
  { productId: "pr3", qty: 1 },
];

// المسافة (كم) بين موقع العميل (الرياض) وموقع كل منشأة
const DISTANCE_KM: Record<string, number> = {
  "biz-rim": 14,
  "biz-tech": 950,
  "biz-fashion": 22,
  "biz-beauty": 400,
  "biz-factory": 410,
  "biz-furniture": 18,
  "biz-services": 940,
  "biz-digital": 9,
};

export default function OrderReview() {
  const { goBack, navigate, params } = useApp();
  const [shipId, setShipId] = useState(
    shippingCompanies.some((s) => s.id === params.shipId) ? String(params.shipId) : shippingCompanies[0].id,
  );
  const [code, setCode] = useState("");
  const [applied, setApplied] = useState(false);
  const [codeError, setCodeError] = useState(false);
  const [coverageIssue, setCoverageIssue] = useState(false);

  // «إكمال الشراء الآن» / «شراء هذا المنتج فقط» يفتح مراجعة الطلب لمنتج واحد.
  const singleProductId = params.productId ? String(params.productId) : "";
  const singleQty = Math.max(1, Number(params.qty) || 1);
  // المنتجات المختارة من السلة بـ Checkbox.
  const selectedCart = params.cartItems
    ? String(params.cartItems)
        .split(",")
        .map((seg) => {
          const [id, q] = seg.split(":");
          return { productId: id, qty: Math.max(1, Number(q) || 1) };
        })
        .filter((l) => l.productId)
    : [];
  const cartLines = singleProductId
    ? [{ productId: singleProductId, qty: singleQty }]
    : selectedCart.length > 0
      ? selectedCart
      : CART;

  const company = shippingCompanies.find((s) => s.id === shipId)!;

  const chosenAddressId = params.addressId ? String(params.addressId) : "";
  const paramAddress = params.addressCity
    ? {
        id: chosenAddressId || "addr-param",
        label: String(params.addressLabel ?? "عنوان التوصيل"),
        name: String(params.addressName ?? ""),
        phone: String(params.addressPhone ?? ""),
        city: String(params.addressCity),
        district: String(params.addressDistrict ?? ""),
        detail: String(params.addressDetail ?? ""),
        isDefault: false,
      }
    : undefined;
  const address =
    paramAddress ??
    savedAddresses.find((a) => a.id === chosenAddressId) ??
    savedAddresses.find((a) => a.isDefault) ??
    savedAddresses[0];
  const fromAddressStep = Boolean(params.shipId || params.addressId);

  const lines = cartLines
    .map((c) => ({ ...c, product: products.find((p) => p.id === c.productId)! }))
    .filter((l) => Boolean(l.product));
  const groups = Array.from(new Set(lines.map((l) => l.product.businessId))).map((bid) => {
    const business = businesses.find((b) => b.id === bid)!;
    const items = lines.filter((l) => l.product.businessId === bid);
    const distance = DISTANCE_KM[bid] ?? 60;
    const shipping = Math.max(1, Math.round(distance * company.pricePerKm));
    return { business, items, distance, shipping };
  });

  const productsTotal = lines.reduce((s, l) => s + (l.product.price ?? 0) * l.qty, 0);
  const shippingTotal = coverageIssue
    ? groups.slice(0, -1).reduce((s, g) => s + g.shipping, 0)
    : groups.reduce((s, g) => s + g.shipping, 0);
  const discount = applied ? 50 : 0;
  const tax = Math.round(0.15 * Math.max(0, productsTotal + shippingTotal - discount));
  const grand = productsTotal + shippingTotal - discount + tax;

  const applyCode = () => {
    if (code.trim().toUpperCase() === "DSHN10") {
      setApplied(true);
      setCodeError(false);
    } else {
      setApplied(false);
      setCodeError(true);
    }
  };

  return (
    <div className="min-h-full flex flex-col">
      <BackHeader title="مراجعة الطلب" onBack={goBack} />

      <div className="px-4 py-4 space-y-5">
        {singleProductId && (
          <div className="rounded-[14px] bg-accent-50 border border-accent-200 px-3.5 py-3 flex items-start gap-2">
            <i className="ri-shopping-bag-3-line text-[16px] text-accent-700 leading-none mt-0.5 shrink-0" />
            <span className="text-[11.5px] text-foreground-700 leading-relaxed">
              أنت تُكمل شراء هذا المنتج فقط — باقي منتجات سلتك تبقى محفوظة للدفع لاحقًا.
            </span>
          </div>
        )}
        {!singleProductId && selectedCart.length > 0 && (
          <div className="rounded-[14px] bg-accent-50 border border-accent-200 px-3.5 py-3 flex items-start gap-2">
            <i className="ri-checkbox-multiple-line text-[16px] text-accent-700 leading-none mt-0.5 shrink-0" />
            <span className="text-[11.5px] text-foreground-700 leading-relaxed">
              أنت تُكمل شراء المنتجات المختارة من سلتك ({selectedCart.length}) — الباقي يبقى محفوظًا للدفع لاحقًا.
            </span>
          </div>
        )}
        <Card className="space-y-2">
          <div className="flex items-center justify-between">
            <h2 className="text-[15px] font-semibold text-foreground-950">عنوان التوصيل</h2>
            <button
              type="button"
              onClick={() => navigate("checkoutAddress", { ...params, addressId: address.id, shipId })}
              className="text-[12px] font-semibold text-primary-600 hover:text-primary-700 cursor-pointer whitespace-nowrap"
            >
              تغيير
            </button>
          </div>
          <div className="flex items-start gap-2.5">
            <i className="ri-map-pin-2-line text-[15px] text-foreground-500 leading-none mt-0.5 shrink-0" />
            <div className="min-w-0">
              <p className="text-[12.5px] font-semibold text-foreground-950">
                {address.label} • {address.city}
              </p>
              <p className="text-[11.5px] text-foreground-700 mt-1 leading-relaxed">
                {address.district} • {address.detail}
              </p>
              <p className="text-[11px] text-foreground-500 mt-1">
                {address.name} • {address.phone}
              </p>
            </div>
          </div>
        </Card>

        <div className="space-y-3">
          <h2 className="text-[15px] font-semibold text-foreground-950">المنتجات</h2>
          {groups.map((g) => {
            const sub = g.items.reduce((s, l) => s + (l.product.price ?? 0) * l.qty, 0);
            const uncovered = coverageIssue && g === groups[groups.length - 1];
            return (
              <Card key={g.business.id} className="p-0 overflow-hidden">
                <div className="flex items-center gap-3 px-4 py-3 border-b border-background-200">
                  <div className="w-8 h-8 rounded-full overflow-hidden bg-background-200 shrink-0">
                    <img src={g.business.logo} alt={g.business.name} className="w-full h-full object-cover object-top" />
                  </div>
                  <span className="text-[13px] font-semibold text-foreground-950">{g.business.name}</span>
                  <span className="mr-auto text-[11px] text-foreground-500">{g.business.city}</span>
                </div>
                <div className="divide-y divide-background-200">
                  {g.items.map((l) => (
                    <div key={l.productId} className="flex items-center gap-3 px-4 py-3">
                      <div className="w-11 h-11 rounded-[12px] overflow-hidden bg-background-200 shrink-0">
                        <img src={l.product.image} alt={l.product.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 truncate">{l.product.name}</p>
                        <p className="text-[11px] text-foreground-600">الكمية: {l.qty}</p>
                      </div>
                      <span className="text-[13px] font-semibold text-foreground-950 shrink-0">
                        {((l.product.price ?? 0) * l.qty).toLocaleString("en-US")} ر.س
                      </span>
                    </div>
                  ))}
                </div>
                <div className="px-4 py-2.5 bg-background-200/40 space-y-1.5">
                  <div className="flex items-center justify-between">
                    <span className="text-[12px] text-foreground-600">إجمالي المنتجات</span>
                    <span className="text-[13px] font-bold text-foreground-950">{sub.toLocaleString("en-US")} ر.س</span>
                  </div>
                  {uncovered ? (
                    <div className="flex items-center gap-1.5 text-danger-600">
                      <i className="ri-error-warning-line text-[14px] leading-none" />
                      <span className="text-[11.5px] font-medium">لا تتوفر تغطية شحن لهذه المنطقة</span>
                    </div>
                  ) : (
                    <div className="flex items-center justify-between">
                      <span className="text-[11.5px] text-foreground-600">
                        الشحن: {g.distance} كم × {company.pricePerKm} ر.س/كم
                      </span>
                      <span className="text-[12px] font-semibold text-foreground-900">{g.shipping.toLocaleString("en-US")} ر.س</span>
                    </div>
                  )}
                </div>
              </Card>
            );
          })}
        </div>

        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-[15px] font-semibold text-foreground-950">شركة الشحن</h2>
            <span className="text-[11px] text-foreground-500">
              {fromAddressStep ? "مختارة مسبقًا — يمكنك تغييرها" : "تنطبق على الطلب كاملًا"}
            </span>
          </div>
          <div className="space-y-2.5">
            {shippingCompanies.map((s) => {
              const active = shipId === s.id;
              return (
                <button
                  key={s.id}
                  type="button"
                  onClick={() => setShipId(s.id)}
                  className={cn(
                    "w-full flex items-center gap-3.5 rounded-[18px] border p-3.5 cursor-pointer transition-colors text-right",
                    active ? "bg-background-100 border-foreground-950" : "bg-background-100 border-background-200 hover:border-foreground-300",
                  )}
                >
                  <span className={cn("w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0", active ? "border-foreground-950" : "border-background-400")}>
                    {active && <span className="w-2.5 h-2.5 rounded-full bg-foreground-950" />}
                  </span>
                  <div className="w-10 h-10 rounded-full overflow-hidden bg-background-200 shrink-0">
                    <img src={s.logo} alt={s.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">{s.name}</p>
                    <p className="text-[11px] text-foreground-600">{s.eta} • {s.pricePerKm} ر.س/كم</p>
                  </div>
                </button>
              );
            })}
          </div>
          <button
            type="button"
            onClick={() => setCoverageIssue((v) => !v)}
            className="mt-2 text-[11px] text-foreground-400 cursor-pointer"
          >
            {coverageIssue ? "إلغاء تجربة: منطقة خارج التغطية" : "تجربة: منشأة خارج التغطية"}
          </button>
          {coverageIssue && (
            <div className="mt-2.5 flex items-start gap-2 rounded-[14px] bg-danger-50 border border-danger-200 px-3.5 py-3 animate-fade-in">
              <i className="ri-error-warning-line text-[16px] text-danger-600 leading-none mt-0.5" />
              <span className="text-[12px] text-danger-700 leading-relaxed">
                لا توجد شركة شحن تغطي منطقة إحدى المنشآت حاليًا. جرّب اختيار شركة شحن أخرى أو أزل منتجات تلك المنشأة.
              </span>
            </div>
          )}
        </div>

        <div>
          <h2 className="text-[15px] font-semibold text-foreground-950 mb-3">كود الخصم</h2>
          <div className="flex gap-2.5">
            <div className="flex-1 flex items-center h-[52px] rounded-[14px] bg-background-100 border border-background-200 px-4">
              <i className="ri-coupon-3-line text-[18px] text-foreground-500 leading-none mr-2" />
              <input
                value={code}
                onChange={(e) => {
                  setCode(e.target.value);
                  setCodeError(false);
                }}
                placeholder="أدخل كود الخصم"
                className="flex-1 bg-transparent text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body uppercase"
              />
            </div>
            <button
              type="button"
              onClick={applyCode}
              className="h-[52px] px-5 rounded-[14px] bg-primary-500 text-background-50 text-[14px] font-medium cursor-pointer active:scale-[0.98] transition-transform whitespace-nowrap"
            >
              تطبيق
            </button>
          </div>
          {applied && (
            <div className="flex items-center gap-1.5 mt-2.5 text-accent-700">
              <i className="ri-checkbox-circle-fill text-[15px] leading-none" />
              <span className="text-[12px] font-medium">تم تطبيق كود الخصم بنجاح — خصم 50 ر.س</span>
            </div>
          )}
          {codeError && (
            <div className="flex items-center gap-1.5 mt-2.5 text-danger-600">
              <i className="ri-error-warning-line text-[15px] leading-none" />
              <span className="text-[12px] font-medium">كود الخصم غير صالح أو منتهي</span>
            </div>
          )}
          <p className="text-[10.5px] text-foreground-500 mt-2">جرّب كود التجربة: DSHN10</p>
        </div>

        <Card className="space-y-2.5">
          <h2 className="text-[15px] font-semibold text-foreground-950 mb-1">ملخص السعر</h2>
          <div className="flex items-center justify-between text-[13px]">
            <span className="text-foreground-600">إجمالي المنتجات</span>
            <span className="font-semibold text-foreground-900">{productsTotal.toLocaleString("en-US")} ر.س</span>
          </div>
          <div className="flex items-center justify-between text-[13px]">
            <span className="text-foreground-600">تكلفة الشحن</span>
            <span className="font-semibold text-foreground-900">{shippingTotal.toLocaleString("en-US")} ر.س</span>
          </div>
          {discount > 0 && (
            <div className="flex items-center justify-between text-[13px]">
              <span className="text-foreground-600">الخصم</span>
              <span className="font-semibold text-accent-700">- {discount.toLocaleString("en-US")} ر.س</span>
            </div>
          )}
          <div className="flex items-center justify-between text-[13px]">
            <span className="text-foreground-600">الضريبة (15%)</span>
            <span className="font-semibold text-foreground-900">{tax.toLocaleString("en-US")} ر.س</span>
          </div>
          <div className="flex items-center justify-between pt-2.5 border-t border-background-200">
            <span className="text-[13.5px] font-semibold text-foreground-950">الإجمالي النهائي</span>
            <span className="text-[18px] font-bold text-foreground-950">{grand.toLocaleString("en-US")} ر.س</span>
          </div>
        </Card>
      </div>

      <div className="sticky bottom-0 z-30 mt-auto p-4 bg-background-50/95 backdrop-blur border-t border-background-200/70">
        <button
          type="button"
          disabled={coverageIssue}
          onClick={() => navigate("payment")}
          className="w-full h-[52px] rounded-[14px] bg-primary-500 text-background-50 text-[15px] font-semibold cursor-pointer active:scale-[0.98] transition-transform disabled:opacity-40 disabled:pointer-events-none"
        >
          متابعة
        </button>
      </div>
    </div>
  );
}