import { useState } from "react";
import { businesses } from "@/mocks/dshn";
import { products } from "@/mocks/dshnCommerce";
import { useWeb } from "../WebContext";
import { Container, WBtn, WCard, StatusPill, PriceWeb, cn, fmt } from "../WebUI";

const CAT_NAMES: Record<string, string> = {
  food: "أغذية ومشروبات",
  electronics: "إلكترونيات",
  fashion: "أزياء",
  beauty: "منتجات تجميل",
  industrial: "منتجات صناعية",
  furniture: "أثاث",
  services: "خدمات",
  digital: "منتجات رقمية",
};

export default function ProductDetail() {
  const { params, navigate, addToCart, requireAuth } = useWeb();
  const product = products.find((p) => p.id === params.productId) ?? products[0];
  const business = businesses.find((b) => b.id === product.businessId);
  const gallery = [product.image, product.image, product.image];
  const [active, setActive] = useState(0);
  const [qty, setQty] = useState(product.minOrder);
  const out = product.stock === 0;
  const unpriced = product.negotiable || product.price === null;

  return (
    <div className="animate-fade-in">
      <Container className="py-8">
        <nav className="flex items-center gap-2 text-[12.5px] text-foreground-500 mb-6">
          <button type="button" onClick={() => navigate("products", { categoryId: "" })} className="hover:text-foreground-950 cursor-pointer">المنتجات</button>
          <i className="ri-arrow-left-s-line text-[14px] leading-none" />
          <span className="text-foreground-800 font-medium">{product.name}</span>
        </nav>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Gallery */}
          <div>
            <div className="w-full aspect-square rounded-[24px] overflow-hidden bg-background-100 border border-background-200">
              <img src={gallery[active]} alt={product.name} className="w-full h-full object-cover object-top" />
            </div>
            <div className="flex items-center gap-3 mt-4">
              {gallery.map((img, i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => setActive(i)}
                  className={cn(
                    "w-20 h-20 rounded-[16px] overflow-hidden border-2 transition-colors cursor-pointer",
                    active === i ? "border-primary-500" : "border-background-200 hover:border-background-300",
                  )}
                >
                  <img src={img} alt={`${product.name} ${i + 1}`} className="w-full h-full object-cover object-top" />
                </button>
              ))}
            </div>
          </div>

          {/* Info */}
          <div>
            <h1 className="text-[28px] md:text-[32px] font-bold text-foreground-950 font-heading leading-snug">{product.name}</h1>
            <div className="mt-4">
              <PriceWeb price={product.price} negotiable={product.negotiable} size="text-[32px]" />
            </div>

            <div className="flex flex-wrap items-center gap-2.5 mt-5">
              <StatusPill tone="info" icon="ri-apps-2-line">القسم: {CAT_NAMES[product.categoryId] ?? product.categoryId}</StatusPill>
              {out ? (
                <StatusPill tone="danger" icon="ri-close-circle-line">نفد المخزون</StatusPill>
              ) : (
                <StatusPill tone="success" icon="ri-checkbox-circle-line">متوفر</StatusPill>
              )}
            </div>

            <p className="text-[14.5px] text-foreground-700 leading-relaxed mt-6">{product.description}</p>

            <div className="grid grid-cols-2 gap-4 mt-6">
              <InfoBox label="الكمية المتاحة" value={`${fmt(product.stock)}`} />
              <InfoBox label="الحد الأدنى للطلب" value={`${fmt(product.minOrder)}`} />
            </div>

            {business && (
              <WCard className="p-4 flex items-center gap-3.5 mt-6" onClick={() => navigate("business", { businessId: business.id })}>
                <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
                  <img src={business.logo} alt={business.name} className="w-full h-full object-cover object-top" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[14px] font-semibold text-foreground-950">{business.name}</p>
                  <p className="text-[11.5px] text-foreground-600">{business.activity} • {business.city}</p>
                </div>
                <i className="ri-arrow-left-line text-[18px] text-foreground-400 leading-none" />
              </WCard>
            )}

            {!out && (
              <div className="flex items-center gap-4 mt-6">
                <span className="text-[13.5px] font-semibold text-foreground-800">الكمية</span>
                <div className="flex items-center gap-3">
                  <StepBtn icon="ri-add-line" onClick={() => setQty((q) => Math.min(product.stock, q + 1))} />
                  <span className="w-10 text-center text-[17px] font-bold text-foreground-950">{qty}</span>
                  <StepBtn icon="ri-subtract-line" onClick={() => setQty((q) => Math.max(1, q - 1))} />
                </div>
                {qty < product.minOrder && (
                  <span className="text-[12px] text-danger-600">الحد الأدنى للطلب {product.minOrder}</span>
                )}
              </div>
            )}

            <div className="flex flex-col sm:flex-row gap-3 mt-7">
              {out ? (
                <WBtn variant="secondary" className="flex-1" disabled>نفد المخزون</WBtn>
              ) : unpriced ? (
                <WBtn className="flex-1" onClick={() => requireAuth("customer", () => navigate("chats"))} icon="ri-chat-3-line">
                  طلب عن طريق المحادثة
                </WBtn>
              ) : (
                <>
                  <WBtn
                    className="flex-1"
                    icon="ri-shopping-bag-line"
                    onClick={() => requireAuth("customer", () => addToCart(qty))}
                  >
                    إضافة للسلة
                  </WBtn>
                  <WBtn
                    variant="secondary"
                    className="flex-1"
                    onClick={() => requireAuth("customer", () => navigate("checkoutAddress", { productId: product.id, qty: String(qty) }))}
                  >
                    شراء الآن
                  </WBtn>
                </>
              )}
            </div>
            <p className="text-[12px] text-foreground-500 mt-3">
              لا يمكن إلغاء الطلب بعد الدفع — النزاعات هي المسار الوحيد للخلافات.
            </p>
          </div>
        </div>
      </Container>
    </div>
  );
}

function StepBtn({ icon, onClick }: { icon: string; onClick: () => void }) {
  return (
    <button type="button" onClick={onClick} className="w-10 h-10 rounded-full border border-background-300 flex items-center justify-center text-foreground-950 hover:bg-background-200 cursor-pointer">
      <i className={cn(icon, "text-[18px] leading-none")} />
    </button>
  );
}

function InfoBox({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-[16px] bg-background-100 border border-background-200 p-4">
      <p className="text-[12px] text-foreground-600">{label}</p>
      <p className="text-[17px] font-bold text-foreground-950 mt-1">{value}</p>
    </div>
  );
}