import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { Badge } from "@/pages/app/components/ui";
import { BizTopBar } from "@/pages/app/components/biz/BizUI";
import { ConfirmModal } from "@/pages/app/components/bo/BoUI";
import { PRODUCT_STATUS_META as STATUS_META, productStatusOf } from "@/pages/app/lib/productStatus";
import type { MerchantProduct, MerchantProductStatus } from "@/mocks/dshnBusiness";

type Filter = "all" | MerchantProductStatus;

const CHIP_ORDER: Filter[] = ["all", "active", "out", "hidden", "rejected"];

const CHIP_LABELS: Record<Filter, string> = {
  all: "الكل",
  active: "نشط",
  out: "نفد المخزون",
  hidden: "مخفي",
  rejected: "مرفوض",
};

export default function BizProducts() {
  const { navigate, products, setProductStatus } = useApp();
  const [removed, setRemoved] = useState<string[]>([]);
  const [filter, setFilter] = useState<Filter>("all");
  // Hiding a live product takes it off the storefront, so we always confirm first.
  const [confirmHide, setConfirmHide] = useState<MerchantProduct | null>(null);

  const list = products.filter((p) => !removed.includes(p.id));

  // Live counters per status (derived from the actual products).
  const counts: Record<Filter, number> = { all: list.length, active: 0, out: 0, hidden: 0, rejected: 0 };
  list.forEach((p) => {
    counts[productStatusOf(p)] += 1;
  });

  const visibleList = filter === "all" ? list : list.filter((p) => productStatusOf(p) === filter);

  const showProduct = (p: MerchantProduct) => setProductStatus(p.id, p.stock > 0 ? "active" : "out");

  return (
    <div className="min-h-full bg-background-50 pb-6">
      {/* Sticky header block: title bar + status filter row (stays visible while scrolling) */}
      <div className="sticky top-0 z-20">
        <BizTopBar title="إدارة المنتجات" />

        <div className="bg-background-50 border-b border-background-200/70">
          <div
            className="flex overflow-x-auto no-scrollbar px-4 pt-1 pb-3"
            style={{ flexWrap: "nowrap", gap: 8, WebkitOverflowScrolling: "touch" }}
          >
            {CHIP_ORDER.map((id) => {
              const isActive = filter === id;
              return (
                <button
                  key={id}
                  type="button"
                  onClick={() => setFilter(id)}
                  className={`h-10 shrink-0 whitespace-nowrap rounded-full px-4 text-[13px] font-semibold transition-colors cursor-pointer ${
                    isActive
                      ? "bg-foreground-950 text-background-50"
                      : "bg-background-50 border border-background-300 text-foreground-600"
                  }`}
                >
                  {CHIP_LABELS[id]} ({counts[id]})
                </button>
              );
            })}
          </div>
        </div>
      </div>

      <div className="px-4 mt-3 space-y-3">
        {visibleList.length === 0 ? (
          <p className="text-center text-[13px] text-foreground-600 py-14">لا توجد منتجات في هذه الحالة</p>
        ) : (
          visibleList.map((p) => {
            const status = productStatusOf(p);
            const meta = STATUS_META[status];
            const rejected = status === "rejected";
            const visible = status !== "hidden";
            const detailsScreen =
              status === "out"
                ? "bizProductDetailsOut"
                : p.negotiable
                  ? "bizProductDetailsNegotiable"
                  : "bizProductDetails";
            return (
              <div
                key={p.id}
                onClick={() => navigate(detailsScreen, { productId: p.id })}
                className="rounded-[18px] bg-background-100 border border-background-200 p-3 cursor-pointer hover:border-background-300 transition-colors"
              >
                <div className="flex gap-3">
                  <div className="w-[68px] h-[68px] rounded-[14px] overflow-hidden bg-background-200 shrink-0">
                    <img src={p.image} alt={p.name} className="w-full h-full object-cover object-top" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-2">
                      <h3 className="text-[13px] font-semibold text-foreground-950 leading-snug line-clamp-2">{p.name}</h3>
                      <Badge tone={meta.tone}>{meta.label}</Badge>
                    </div>
                    <div className="mt-2">
                      {p.negotiable ? (
                        <span className="inline-flex rounded-full bg-secondary-100 text-secondary-900 px-2.5 py-1 text-[10.5px] font-semibold">
                          حسب التفاوض
                        </span>
                      ) : (
                        <span className="text-[14px] font-bold text-foreground-950">
                          {p.price?.toLocaleString("en-US")} <span className="text-[11px]">ر.س</span>
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {rejected && (
                  <div className="mt-3 rounded-[12px] bg-danger-50 border border-danger-200 px-3 py-2">
                    <p className="text-[11.5px] text-danger-700 leading-relaxed">
                      المنتج مرفوض ولا يظهر للعملاء. عدّله وأعد إرساله ليتم إظهاره.
                    </p>
                  </div>
                )}

                <div className="mt-3 pt-3 border-t border-background-200 flex items-center gap-2">
                  {rejected ? (
                    /* Rejected products can never be switched back on directly */
                    <span
                      aria-label="المنتج مرفوض — لا يمكن إظهاره"
                      title="المنتج مرفوض — لا يمكن إظهاره"
                      className="relative w-[48px] h-[28px] rounded-full shrink-0 bg-background-300 flex items-center justify-center"
                    >
                      <i className="ri-lock-line text-[13px] text-foreground-500 leading-none" />
                    </span>
                  ) : (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        if (visible) {
                          setConfirmHide(p);
                        } else {
                          showProduct(p);
                        }
                      }}
                      aria-label={visible ? "إخفاء المنتج" : "إظهار المنتج"}
                      className={`relative w-[48px] h-[28px] rounded-full shrink-0 transition-colors cursor-pointer ${
                        visible ? "bg-accent-500" : "bg-background-300"
                      }`}
                    >
                      <span
                        className={`absolute top-1 w-[20px] h-[20px] rounded-full bg-background-50 transition-all ${
                          visible ? "right-1" : "right-[26px]"
                        }`}
                      />
                    </button>
                  )}

                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      navigate("bizProductEdit", { productId: p.id });
                    }}
                    aria-label={rejected ? "تعديل وإعادة الإرسال" : "تعديل المنتج"}
                    className={`h-10 rounded-[12px] border flex items-center justify-center gap-1.5 cursor-pointer shrink-0 ${
                      rejected
                        ? "px-3 border-primary-500 bg-primary-500 text-background-50 text-[12px] font-semibold"
                        : "w-10 border-background-300 text-foreground-900 hover:bg-background-200"
                    }`}
                  >
                    <i className="ri-edit-line text-[17px] leading-none" />
                    {rejected && <span className="whitespace-nowrap">إعادة الإرسال</span>}
                  </button>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      setRemoved((r) => [...r, p.id]);
                    }}
                    aria-label="حذف المنتج"
                    className="w-10 h-10 rounded-[12px] border border-danger-200 text-danger-600 flex items-center justify-center cursor-pointer hover:bg-danger-50 shrink-0"
                  >
                    <i className="ri-delete-bin-line text-[17px] leading-none" />
                  </button>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* floating (+) button — in normal flow, above the bottom nav (never overlapping) */}
      <div className="px-4 pt-5 pb-2 flex justify-start">
        <button
          type="button"
          onClick={() => navigate("bizProductForm")}
          aria-label="إضافة منتج"
          className="w-14 h-14 rounded-full bg-primary-500 text-background-50 flex items-center justify-center cursor-pointer active:scale-95 transition-transform"
        >
          <i className="ri-add-line text-[26px] leading-none" />
        </button>
      </div>

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