import { useRef } from "react";
import { businesses } from "@/mocks/dshn";
import { products } from "@/mocks/dshnCommerce";
import { investorOpportunities } from "@/mocks/dshnInvestor";
import { myBusiness } from "@/mocks/dshnBusiness";
import { useWeb } from "@/pages/web/WebContext";
import { Container, WCard, PriceWeb, cn, fmt } from "@/pages/web/WebUI";

function millions(n: number): string {
  const m = n / 1000000;
  const label = Number.isInteger(m) ? String(m) : m.toFixed(1);
  return `${label}م ر.س`;
}

const ACTION_BASE =
  "w-full h-12 rounded-[14px] text-[14.5px] font-semibold inline-flex items-center justify-center gap-2 whitespace-nowrap transition-colors cursor-pointer";

export default function Business() {
  const { params, navigate, toggleFavorite, requireAuth, favorites, role } = useWeb();
  const business = businesses.find((b) => b.id === params.businessId) ?? businesses[0];
  const op = investorOpportunities.find((o) => o.businessId === business.id);
  const list = products.filter((p) => p.businessId === business.id);
  const isFav = favorites.includes(business.id);
  const productsRef = useRef<HTMLDivElement>(null);

  const isInvestor = role === "investor";
  const isOwner = role === "business";
  const isOwnBusiness = isOwner && business.id === myBusiness.id;

  const scrollToProducts = () =>
    productsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });

  return (
    <div className="animate-fade-in">
      <Container className="py-8">
        {/* ── Cover ─────────────────────────────────────────────── */}
        <div className="relative h-[240px] md:h-[280px] rounded-[24px] overflow-hidden bg-background-200">
          <img
            src={business.cover}
            alt={business.name}
            className="w-full h-full object-cover object-top"
          />
        </div>

        {/* ── Identity row (overlaps the cover bottom) ──────────── */}
        <div className="relative z-10 -mt-14 px-4 md:px-6 flex flex-col md:flex-row md:items-end md:justify-between gap-4">
          <div className="flex items-end gap-5 min-w-0">
            <div className="w-[96px] h-[96px] md:w-[112px] md:h-[112px] rounded-full overflow-hidden bg-background-100 border-4 border-background-50 shrink-0">
              <img
                src={business.logo}
                alt={business.name}
                className="w-full h-full object-cover object-top"
              />
            </div>
            <div className="pb-1.5 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <h1 className="text-[24px] md:text-[28px] font-bold text-foreground-950 font-heading leading-tight">
                  {business.name}
                </h1>
                {business.verified && (
                  <span className="inline-flex items-center gap-1 text-accent-700 text-[13.5px] font-semibold">
                    <i className="ri-verified-badge-fill text-[18px] leading-none" />
                    موثّق
                  </span>
                )}
              </div>
              <p className="text-[14px] text-foreground-600 mt-1.5">
                {business.activity} • {business.city}
              </p>
            </div>
          </div>

          <button
            type="button"
            onClick={() => requireAuth("customer", () => toggleFavorite(business.id))}
            className={cn(
              "h-11 px-4 rounded-full inline-flex items-center gap-2 text-[13.5px] font-semibold whitespace-nowrap cursor-pointer transition-colors shrink-0 self-start md:self-auto",
              isFav
                ? "bg-danger-500 border border-danger-500 text-background-50"
                : "bg-background-50 border border-background-300 text-foreground-800 hover:border-foreground-400",
            )}
          >
            <i className={cn(isFav ? "ri-heart-fill" : "ri-heart-line", "text-[18px] leading-none")} />
            إضافة للمفضلة
          </button>
        </div>

        {/* ── Two columns: main (right) + side (left) ───────────── */}
        <div className="flex flex-col lg:flex-row items-start gap-6 mt-9">
          {/* MAIN column (right in RTL) */}
          <div className="w-full min-w-0 flex-1 space-y-6">
            {/* Description */}
            <WCard className="p-6 md:p-7">
              <h2 className="text-[18px] font-bold text-foreground-950 mb-3">الوصف</h2>
              <p className="text-[14.5px] text-foreground-700 leading-relaxed">
                {business.description}
              </p>
            </WCard>

            {/* Partnerships */}
            {business.partners.length > 0 && (
              <WCard className="p-6 md:p-7">
                <h2 className="text-[18px] font-bold text-foreground-950 mb-4">الشراكات</h2>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {business.partners.map((p) => (
                    <button
                      key={p.name}
                      type="button"
                      onClick={() => navigate("businesses")}
                      className="flex items-center gap-3 rounded-[16px] bg-background-50 border border-background-200 px-3.5 py-3 text-start transition-colors hover:border-background-300 cursor-pointer"
                    >
                      <div className="w-10 h-10 rounded-full overflow-hidden bg-background-200 shrink-0">
                        <img
                          src={p.logo}
                          alt={p.name}
                          className="w-full h-full object-cover object-top"
                        />
                      </div>
                      <span className="flex-1 min-w-0 text-[13.5px] font-semibold text-foreground-900 truncate">
                        {p.name}
                      </span>
                      <i className="ri-arrow-left-s-line text-[18px] text-foreground-400 leading-none shrink-0" />
                    </button>
                  ))}
                </div>
              </WCard>
            )}

            {/* Products */}
            <div ref={productsRef} className="scroll-mt-[140px]">
              <WCard className="p-6 md:p-7">
                <div className="flex items-center gap-2.5 mb-5">
                  <h2 className="text-[18px] font-bold text-foreground-950">منتجات المنشأة</h2>
                  <span className="inline-flex items-center rounded-full bg-background-200 text-foreground-700 px-2.5 py-0.5 text-[12px] font-semibold">
                    {list.length}
                  </span>
                </div>

                {list.length === 0 ? (
                  <div className="flex flex-col items-center justify-center text-center py-14">
                    <div className="w-16 h-16 rounded-full bg-background-200 flex items-center justify-center mb-4">
                      <i className="ri-store-2-line text-[30px] text-foreground-500 leading-none" />
                    </div>
                    <p className="text-[14px] text-foreground-600">لا توجد منتجات معروضة حاليًا</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                    {list.map((p) => (
                      <ProductTile
                        key={p.id}
                        name={p.name}
                        image={p.image}
                        price={p.price}
                        negotiable={p.negotiable}
                        businessName={business.name}
                        out={p.stock === 0}
                        onClick={() => navigate("product", { productId: p.id })}
                      />
                    ))}
                  </div>
                )}
              </WCard>
            </div>
          </div>

          {/* SIDE column (left in RTL) — ONE sticky card */}
          <aside className="w-full lg:w-[360px] shrink-0 lg:sticky lg:top-[140px]">
            <WCard className="p-6">
              {/* Metrics */}
              <div className="space-y-4">
                <MetricRow icon="ri-line-chart-line" label="المبيعات السنوية" value={millions(business.annualSales)} />
                <MetricRow
                  icon="ri-money-dollar-circle-line"
                  label="التقييم الحالي"
                  value={`${fmt(business.estimatedValue)} ر.س`}
                />
                <MetricRow icon="ri-calendar-line" label="تاريخ آخر تقييم" value={business.lastRating} />
              </div>

              {/* Opportunity summary — only when the business has one */}
              {op && (
                <>
                  <div className="h-px bg-background-200 my-5" />
                  <div className="rounded-[16px] border border-secondary-300 bg-secondary-50 p-4">
                    <span className="inline-flex items-center gap-1 rounded-full bg-secondary-500 text-secondary-950 px-3 py-1 text-[11.5px] font-bold">
                      <i className="ri-flashlight-fill text-[13px] leading-none" />
                      فرصة استثمار
                    </span>
                    <h3 className="text-[15px] font-bold text-foreground-950 mt-3">تبحث عن مستثمر</h3>
                    <div className="mt-3.5 space-y-2.5 text-[13.5px]">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-foreground-600">مبلغ الاستثمار</span>
                        <span className="font-bold text-foreground-950 whitespace-nowrap">
                          {fmt(op.amount)} ر.س
                        </span>
                      </div>
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-foreground-600">النسبة المعروضة</span>
                        <span className="font-bold text-secondary-800 whitespace-nowrap">{op.equity}%</span>
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => navigate("opportunity", { opportunityId: op.id })}
                      className="mt-4 w-full inline-flex items-center justify-center gap-1 text-[13.5px] font-semibold text-foreground-950 hover:underline underline-offset-4 cursor-pointer"
                    >
                      عرض التفاصيل
                      <i className="ri-arrow-left-line text-[16px] leading-none" />
                    </button>
                  </div>
                </>
              )}

              {/* Main action by role */}
              <div className="mt-6">
                {isOwner ? (
                  isOwnBusiness ? (
                    <button
                      type="button"
                      onClick={() => navigate("biz", { bizRoute: "biz-manage" })}
                      className={cn(
                        ACTION_BASE,
                        "bg-background-50 border border-foreground-950 text-foreground-950 hover:bg-background-200",
                      )}
                    >
                      <i className="ri-edit-box-line text-[18px] leading-none" />
                      تعديل بيانات المنشأة
                    </button>
                  ) : (
                    <button
                      type="button"
                      onClick={() => navigate("biz", { bizRoute: "biz-partner-chat" })}
                      className={cn(ACTION_BASE, "bg-primary-500 text-background-50 hover:bg-primary-600")}
                    >
                      <i className="ri-team-line text-[18px] leading-none" />
                      طلب شراكة
                    </button>
                  )
                ) : isInvestor ? (
                  <button
                    type="button"
                    onClick={() =>
                      op ? navigate("invOffer", { opportunityId: op.id }) : navigate("invOpps")
                    }
                    className={cn(ACTION_BASE, "bg-primary-500 text-background-50 hover:bg-primary-600")}
                  >
                    <i className="ri-hand-coin-line text-[18px] leading-none" />
                    طلب استثمار
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={scrollToProducts}
                    className={cn(ACTION_BASE, "bg-primary-500 text-background-50 hover:bg-primary-600")}
                  >
                    <i className="ri-store-2-line text-[18px] leading-none" />
                    استعراض المنتجات
                  </button>
                )}
              </div>
            </WCard>
          </aside>
        </div>
      </Container>
    </div>
  );
}

function MetricRow({ icon, label, value }: { icon: string; label: string; value: string }) {
  return (
    <div className="flex items-center gap-3">
      <span className="w-10 h-10 rounded-[12px] bg-accent-100 text-accent-800 flex items-center justify-center shrink-0">
        <i className={cn(icon, "text-[19px] leading-none")} />
      </span>
      <div className="min-w-0 flex-1">
        <p className="text-[12px] text-foreground-600">{label}</p>
        <p className="text-[15.5px] font-bold text-foreground-950 whitespace-nowrap">{value}</p>
      </div>
    </div>
  );
}

function ProductTile({
  name,
  image,
  price,
  negotiable,
  businessName,
  out,
  onClick,
}: {
  name: string;
  image: string;
  price: number | null;
  negotiable: boolean;
  businessName: string;
  out: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="text-start bg-background-50 border border-background-200 rounded-[18px] overflow-hidden transition-colors hover:border-background-300 cursor-pointer"
    >
      <div className={cn("relative w-full aspect-square bg-background-200", out && "opacity-60")}>
        <img src={image} alt={name} className="w-full h-full object-cover object-top" />
        {out && (
          <span className="absolute top-2.5 end-2.5 rounded-full bg-danger-500 text-background-50 px-2.5 py-1 text-[11px] font-bold whitespace-nowrap">
            نفد المخزون
          </span>
        )}
      </div>
      <div className="p-4">
        <h3 className="text-[13.5px] font-semibold text-foreground-950 leading-snug line-clamp-2 h-10">
          {name}
        </h3>
        <div className="mt-2.5">
          <PriceWeb price={price} negotiable={negotiable} size="text-[16px]" />
        </div>
        <p className="text-[12px] text-foreground-500 mt-2 truncate">{businessName}</p>
      </div>
    </button>
  );
}