import { useRef, useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { Badge, BackHeader, Btn } from "@/pages/app/components/ui";
import { ConfirmModal } from "@/pages/app/components/bo/BoUI";
import { PRODUCT_STATUS_META, productStatusOf } from "@/pages/app/lib/productStatus";
import { productHistoryOf } from "@/pages/app/lib/productHistory";
import ProductHistoryLog from "@/pages/app/components/biz/ProductHistoryLog";

export type BizProductDetailsVariant = "fixed" | "negotiable" | "out";

const STATUS_META = PRODUCT_STATUS_META;

/** Default product shown for each fixed state page when no id is passed. */
const DEFAULT_ID: Record<BizProductDetailsVariant, string> = {
  fixed: "mp1",
  negotiable: "mp4",
  out: "mp3",
};

/** Product image galleries (main image + extra shots). */
const GALLERIES: Record<string, string[]> = {
  mp1: [
    "https://readdy.ai/api/search-image?query=Luxury%20Sidr%20honey%20jar%20with%20golden%20honey%20on%20soft%20cream%20studio%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20product%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-honey&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Golden%20Sidr%20honey%20dripping%20from%20a%20wooden%20dipper%20into%20a%20glass%20jar%20on%20soft%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-honey-2&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Top%20view%20of%20a%20honey%20jar%20with%20honeycomb%20pieces%20and%20dates%20on%20a%20soft%20cream%20surface%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-honey-3&orientation=squarish",
  ],
  mp2: [
    "https://readdy.ai/api/search-image?query=Premium%20Medjool%20dates%20in%20an%20elegant%20box%20on%20soft%20cream%20studio%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-dates&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Medjool%20dates%20arranged%20in%20a%20ceramic%20bowl%20on%20a%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-dates-2&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Close%20up%20of%20glossy%20Medjool%20dates%20with%20a%20palm%20leaf%20on%20a%20cream%20surface%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-dates-3&orientation=squarish",
  ],
  mp3: [
    "https://readdy.ai/api/search-image?query=Premium%20extra%20virgin%20olive%20oil%20bottle%20on%20a%20soft%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-oil&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Extra%20virgin%20olive%20oil%20bottle%20beside%20fresh%20olives%20and%20green%20branches%20on%20a%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography&width=600&height=600&seq=dshn-prod-oil-2&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Olive%20oil%20being%20poured%20into%20a%20small%20bowl%20surrounded%20by%20olives%20on%20a%20cream%20surface%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography&width=600&height=600&seq=dshn-prod-oil-3&orientation=squarish",
  ],
  mp4: [
    "https://readdy.ai/api/search-image?query=Luxury%20gift%20hamper%20box%20with%20assorted%20gourmet%20items%20on%20a%20soft%20cream%20background%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20product%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-giftbox&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Open%20luxury%20gift%20box%20revealing%20assorted%20gourmet%20treats%20on%20a%20soft%20cream%20background%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20product%20photography&width=600&height=600&seq=dshn-prod-giftbox-2&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Close%20up%20of%20a%20luxury%20gift%20hamper%20with%20a%20gold%20ribbon%20on%20a%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20photography&width=600&height=600&seq=dshn-prod-giftbox-3&orientation=squarish",
  ],
  mp5: [
    "https://readdy.ai/api/search-image?query=Luxury%20assorted%20roasted%20nuts%20in%20a%20bowl%20on%20a%20soft%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-nuts&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Assorted%20roasted%20nuts%20scattered%20on%20a%20cream%20surface%20from%20above%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography&width=600&height=600&seq=dshn-prod-nuts-2&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Bowl%20of%20mixed%20roasted%20almonds%20and%20cashews%20on%20a%20cream%20background%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography&width=600&height=600&seq=dshn-prod-nuts-3&orientation=squarish",
  ],
  mp6: [
    "https://readdy.ai/api/search-image?query=Elegant%20Arabic%20coffee%20beans%20package%20on%20a%20soft%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20product%20photography%2C%20high%20detail&width=600&height=600&seq=dshn-prod-coffee&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Arabic%20coffee%20cup%20with%20cardamom%20and%20saffron%20on%20a%20cream%20background%2C%20minimal%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20product%20photography&width=600&height=600&seq=dshn-prod-coffee-2&orientation=squarish",
    "https://readdy.ai/api/search-image?query=Roasted%20Arabic%20coffee%20beans%20with%20cardamom%20pods%20on%20a%20cream%20surface%2C%20minimal%20elegant%20composition%2C%20warm%20natural%20light%2C%20editorial%20food%20photography&width=600&height=600&seq=dshn-prod-coffee-3&orientation=squarish",
  ],
};

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-3 px-4 py-3.5">
      <span className="text-[13px] text-foreground-600 shrink-0">{label}</span>
      <span className="text-[13.5px] font-semibold text-foreground-950 text-left">{value}</span>
    </div>
  );
}

export default function BizProductDetails({ variant }: { variant: BizProductDetailsVariant }) {
  const { goBack, params, jump, products, setProductStatus } = useApp();
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [confirmHide, setConfirmHide] = useState(false);
  const [active, setActive] = useState(0);
  const trackRef = useRef<HTMLDivElement>(null);

  const wantedId = params.productId ?? DEFAULT_ID[variant];
  const product =
    products.find((p) => p.id === wantedId) ??
    products.find((p) => p.id === DEFAULT_ID[variant]) ??
    products[0];

  const images = GALLERIES[product.id] ?? [product.image];
  // Status is derived (zero stock => out) so the badge never lies.
  const status = productStatusOf(product);
  const meta = STATUS_META[status];
  const history = productHistoryOf(product);
  const rejected = status === "rejected";
  const hidden = status === "hidden";

  /** Hiding/showing only applies to live products — never to a rejected one. */
  const handleShow = () => setProductStatus(product.id, product.stock > 0 ? "active" : "out");

  const handleScroll = () => {
    const el = trackRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const center = rect.left + rect.width / 2;
    let best = 0;
    let bestDistance = Number.POSITIVE_INFINITY;
    Array.from(el.children).forEach((child, i) => {
      const r = (child as HTMLElement).getBoundingClientRect();
      const distance = Math.abs(r.left + r.width / 2 - center);
      if (distance < bestDistance) {
        bestDistance = distance;
        best = i;
      }
    });
    setActive(best);
  };

  const goToImage = (index: number) => {
    const el = trackRef.current;
    if (!el) return;
    const child = el.children[index] as HTMLElement | undefined;
    child?.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
    setActive(index);
  };

  return (
    <div className="relative min-h-full bg-background-50 pb-8">
      <BackHeader title="تفاصيل المنتج" onBack={goBack} />

      <div className="px-4 py-4 space-y-4">
        {/* Image gallery */}
        <div>
          <div
            ref={trackRef}
            onScroll={handleScroll}
            className="flex overflow-x-auto no-scrollbar snap-x snap-mandatory rounded-[20px] bg-background-200"
          >
            {images.map((src, i) => (
              <div key={i} className="w-full shrink-0 snap-center aspect-square bg-background-200">
                <img src={src} alt={product.name} className="w-full h-full object-cover object-top" />
              </div>
            ))}
          </div>

          {/* Dots indicator */}
          <div className="relative">
            <div className="-mt-7 flex justify-center">
              <div className="flex items-center gap-1.5 rounded-full bg-foreground-950/35 px-2.5 py-1.5 backdrop-blur-sm">
                {images.map((_, i) => (
                  <span
                    key={i}
                    className={`h-1.5 rounded-full transition-all ${
                      i === active ? "w-5 bg-background-50" : "w-1.5 bg-background-50/60"
                    }`}
                  />
                ))}
              </div>
            </div>
          </div>

          {/* Thumbnails */}
          <div className="flex gap-2 mt-3">
            {images.map((src, i) => (
              <button
                key={i}
                type="button"
                onClick={() => goToImage(i)}
                aria-label={`صورة ${i + 1}`}
                className={`w-16 h-16 rounded-[12px] overflow-hidden border-2 cursor-pointer transition-colors ${
                  i === active ? "border-foreground-950" : "border-background-200"
                }`}
              >
                <img src={src} alt={product.name} className="w-full h-full object-cover object-top" />
              </button>
            ))}
          </div>
        </div>

        {/* Name + status */}
        <div className="flex items-start justify-between gap-3">
          <h2 className="text-[18px] font-bold text-foreground-950 leading-snug">{product.name}</h2>
          <Badge tone={meta.tone}>{meta.label}</Badge>
        </div>

        {rejected && (
          <div className="rounded-[20px] bg-danger-50 border border-danger-200 p-4">
            <div className="flex items-start gap-2.5">
              <span className="w-8 h-8 rounded-full bg-danger-100 text-danger-700 flex items-center justify-center shrink-0">
                <i className="ri-error-warning-line text-[17px] leading-none" />
              </span>
              <div className="min-w-0">
                <p className="text-[14px] font-bold text-danger-800">المنتج مرفوض ولا يظهر للعملاء</p>
                {product.rejectedDate && (
                  <p className="text-[11.5px] text-danger-700 mt-0.5">تاريخ الرفض: {product.rejectedDate}</p>
                )}
                <p className="text-[13px] text-danger-700 leading-relaxed mt-2">
                  {product.rejectReason ?? "لم يتم إرفاق سبب للرفض، تواصل مع فريق المراجعة للمزيد."}
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Info card */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 divide-y divide-background-200">
          <InfoRow label="التصنيف" value={product.category} />
          <InfoRow label="طريقة البيع" value={product.negotiable ? "حسب التفاوض" : "سعر محدد"} />
          {!product.negotiable && product.price !== null && (
            <InfoRow label="السعر" value={`${product.price.toLocaleString("en-US")} ر.س`} />
          )}
          <InfoRow label="الحد الأدنى للطلب" value={String(product.minOrder)} />
          <InfoRow label="الكمية المتاحة" value={String(product.stock)} />
        </div>

        {/* Description */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <p className="text-[15px] font-semibold text-foreground-950">الوصف</p>
          <p className="text-[13px] text-foreground-700 leading-relaxed mt-2">{product.description}</p>
        </div>

        {/* Status log: creation, hiding, rejection, resubmission… */}
        <ProductHistoryLog events={history} />

        {/* Actions */}
        <div className="space-y-2.5 pt-1">
          <Btn full onClick={() => jump("bizProductEdit", { productId: product.id })}>
            <i className={rejected ? "ri-send-plane-line text-[18px] leading-none" : "ri-edit-line text-[18px] leading-none"} />
            {rejected ? "تعديل وإعادة الإرسال" : "تعديل المنتج"}
          </Btn>

          {rejected ? (
            <div className="rounded-[14px] bg-background-100 border border-background-200 px-4 py-3 flex items-start gap-2">
              <i className="ri-lock-line text-[16px] text-foreground-500 leading-none mt-0.5 shrink-0" />
              <p className="text-[12px] text-foreground-600 leading-relaxed">
                لا يمكن إظهار المنتج المرفوض قبل تعديله وإعادة إرساله للمراجعة.
              </p>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => (hidden ? handleShow() : setConfirmHide(true))}
              className="w-full h-[52px] rounded-[14px] bg-background-100 text-foreground-900 border border-background-300 text-[16px] font-semibold flex items-center justify-center gap-2 whitespace-nowrap cursor-pointer hover:bg-background-200 transition-colors"
            >
              <i className={`${hidden ? "ri-eye-line" : "ri-eye-off-line"} text-[18px] leading-none`} />
              {hidden ? "إظهار المنتج" : "إخفاء المنتج"}
            </button>
          )}
          <button
            type="button"
            onClick={() => setConfirmOpen(true)}
            className="w-full h-[52px] rounded-[14px] bg-danger-50 text-danger-600 border border-danger-200 text-[16px] font-semibold flex items-center justify-center gap-2 whitespace-nowrap cursor-pointer hover:bg-danger-100 transition-colors"
          >
            <i className="ri-delete-bin-line text-[18px] leading-none" />
            حذف المنتج
          </button>
        </div>
      </div>

      <ConfirmModal
        open={confirmOpen}
        title="حذف المنتج؟"
        desc="سيتم حذف المنتج نهائيًا ولا يمكن التراجع عن هذه العملية."
        confirmLabel="حذف المنتج"
        cancelLabel="إلغاء"
        danger
        onConfirm={() => {
          setConfirmOpen(false);
          jump("bizProducts");
        }}
        onCancel={() => setConfirmOpen(false)}
      />

      <ConfirmModal
        open={confirmHide}
        title="إخفاء المنتج؟"
        desc={`سيتم إخفاء «${product.name}» من صفحة منشأتك ولن يظهر للعملاء. يمكنك إظهاره مرة أخرى في أي وقت.`}
        confirmLabel="إخفاء المنتج"
        cancelLabel="إلغاء"
        danger
        onConfirm={() => {
          setProductStatus(product.id, "hidden");
          setConfirmHide(false);
        }}
        onCancel={() => setConfirmHide(false)}
      />
    </div>
  );
}