import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { businesses } from "@/mocks/dshn";
import { products } from "@/mocks/dshnCommerce";
import { investorOpportunities } from "@/mocks/dshnInvestor";
import { VerifiedBadge } from "@/pages/app/components/BusinessCard";
import BizOwnerProductCard from "@/pages/app/components/biz/BizOwnerProductCard";
import { cn } from "@/pages/app/components/ui";

function fmt(n: number) {
  return n.toLocaleString("en-US");
}

/** Small owner-only action link (clearly not part of the public page). */
function OwnerLink({ icon, label, onClick }: { icon: string; label: string; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="inline-flex items-center gap-1 rounded-full bg-accent-100 border border-accent-200 text-accent-900 px-2.5 py-1 text-[11px] font-semibold whitespace-nowrap cursor-pointer hover:bg-accent-200/70 transition-colors"
    >
      <i className={cn(icon, "text-[12px] leading-none")} />
      {label}
    </button>
  );
}

/**
 * Business-owner preview of the public business page.
 * `empty` renders the version with no published opportunity, no partners and no products.
 */
export default function BizPreview({ empty = false }: { empty?: boolean }) {
  const { navigate, goBack } = useApp();
  const [descOpen, setDescOpen] = useState(false);

  const biz = businesses.find((b) => b.id === "biz-rim") ?? businesses[0];
  const list = empty ? [] : products.filter((p) => p.businessId === biz.id);
  const opp = empty ? undefined : investorOpportunities.find((o) => o.businessId === biz.id);
  const partners = empty ? [] : biz.partners;

  const metrics = [
    { label: "المبيعات السنوية", value: `${(biz.annualSales / 1000000).toFixed(1)}م ر.س`, icon: "ri-line-chart-line" },
    { label: "التقييم الحالي", value: `${(biz.estimatedValue / 1000000).toFixed(1)}م ر.س`, icon: "ri-hand-coin-line" },
    { label: "تاريخ آخر تقييم", value: biz.lastRating, icon: "ri-calendar-line" },
  ];

  return (
    <div dir="rtl" className="flex min-h-full flex-col bg-background-50 font-body text-foreground-950">
      {/* Owner-only preview banner (sticky) */}
      <div className="sticky top-0 z-40 flex items-center gap-2 bg-accent-100 border-b border-accent-200 px-4 pt-[calc(env(safe-area-inset-top)+0.5rem)] pb-2.5">
        <button
          type="button"
          onClick={goBack}
          aria-label="رجوع"
          className="w-8 h-8 rounded-full bg-background-100/80 flex items-center justify-center text-accent-900 cursor-pointer shrink-0"
        >
          <i className="ri-arrow-right-line text-[18px] leading-none" />
        </button>
        <span className="w-6 h-6 rounded-full bg-background-100 flex items-center justify-center shrink-0">
          <i className="ri-eye-line text-[14px] text-accent-800 leading-none" />
        </span>
        <p className="text-[11.5px] font-semibold text-accent-900 leading-tight">
          معاينة: هكذا تظهر صفحة منشأتك للزوار والعملاء
        </p>
      </div>

      {/* Cover + logo (no favorite button) */}
      <div className="relative">
        <div className="relative w-full h-[200px] bg-background-200">
          <img src={biz.cover} alt={biz.name} className="w-full h-full object-cover object-top" />
          <div className="absolute inset-0 bg-gradient-to-t from-foreground-950/30 to-transparent" />
        </div>
        <div className="absolute bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2">
          <div className="w-[88px] h-[88px] rounded-full overflow-hidden border-4 border-background-50 bg-background-200">
            <img src={biz.logo} alt={biz.name} className="w-full h-full object-cover object-top" />
          </div>
        </div>
      </div>

      {/* Basic info */}
      <div className="px-4 pt-14">
        <div className="flex items-center gap-2 flex-wrap">
          <h1 className="text-[22px] font-bold text-foreground-950">{biz.name}</h1>
          {biz.verified && <VerifiedBadge />}
        </div>
        <p className="text-[13px] text-foreground-600 mt-1">
          {biz.activity} • {biz.city}
        </p>
        <p className={cn("text-[13.5px] text-foreground-700 mt-3 leading-relaxed", !descOpen && "line-clamp-3")}>
          {biz.description}
        </p>
        <button
          type="button"
          onClick={() => setDescOpen((v) => !v)}
          className="mt-1 text-[12.5px] font-medium text-accent-700 hover:text-accent-800 cursor-pointer"
        >
          {descOpen ? "عرض أقل" : "اقرأ المزيد"}
        </button>
      </div>

      {/* Metrics */}
      <div className="px-4 mt-5 grid grid-cols-3 gap-2.5">
        {metrics.map((m) => (
          <div key={m.label} className="rounded-[16px] bg-background-100 border border-background-200 p-3 flex flex-col">
            <span className="w-[30px] h-[30px] rounded-full bg-background-200 flex items-center justify-center">
              <i className={cn(m.icon, "text-[16px] text-foreground-700 leading-none")} />
            </span>
            <p className="text-[13px] font-bold text-foreground-950 mt-2.5 leading-tight break-words">{m.value}</p>
            <p className="text-[10px] text-foreground-600 mt-1 leading-tight">{m.label}</p>
          </div>
        ))}
      </div>

      {/* Investment opportunity */}
      <div className="px-4 mt-5">
        {opp ? (
          <>
            <div className="mb-2">
              <OwnerLink icon="ri-settings-3-line" label="إدارة الفرص ‹" onClick={() => navigate("bizOpportunities")} />
            </div>
            <div className="rounded-[20px] bg-secondary-50 border border-secondary-300 p-4">
              <div className="flex items-center gap-2">
                <span className="w-8 h-8 rounded-full bg-secondary-500 flex items-center justify-center">
                  <i className="ri-seedling-fill text-[16px] text-secondary-950 leading-none" />
                </span>
                <h3 className="text-[15px] font-bold text-foreground-950">الفرصة الاستثمارية</h3>
              </div>
              <div className="grid grid-cols-2 gap-2.5 mt-3.5">
                <div>
                  <p className="text-[11px] text-foreground-600">مبلغ الاستثمار المطلوب</p>
                  <p className="text-[16px] font-bold text-foreground-950 mt-0.5">{fmt(opp.amount)} ر.س</p>
                </div>
                <div>
                  <p className="text-[11px] text-foreground-600">نسبة الملكية المعروضة</p>
                  <p className="text-[16px] font-bold text-secondary-900 mt-0.5">{opp.equity}%</p>
                </div>
              </div>
              <button
                type="button"
                onClick={() => navigate("bizOpportunity")}
                className="mt-3.5 w-full h-[46px] rounded-[16px] bg-primary-500 text-background-50 text-[14px] font-semibold whitespace-nowrap cursor-pointer active:scale-[0.98] transition-transform"
              >
                عرض التفاصيل
              </button>
            </div>
          </>
        ) : (
          <div className="rounded-[20px] border-2 border-dashed border-background-300 bg-background-100 p-4 flex flex-col items-center text-center gap-2.5">
            <span className="w-10 h-10 rounded-full bg-background-200 flex items-center justify-center">
              <i className="ri-seedling-line text-[18px] text-foreground-600 leading-none" />
            </span>
            <p className="text-[13px] font-semibold text-foreground-800">لا توجد فرصة استثمارية منشورة</p>
            <OwnerLink icon="ri-add-line" label="إضافة فرصة ‹" onClick={() => navigate("bizOpportunityForm")} />
          </div>
        )}
      </div>

      {/* Partnerships */}
      {partners.length > 0 && (
        <div className="px-4 mt-6">
          <h2 className="text-[17px] font-semibold text-foreground-950">الشراكات</h2>
          <div className="flex gap-2.5 overflow-x-auto no-scrollbar mt-3 pb-1">
            {partners.map((p) => (
              <button
                key={p.name}
                type="button"
                onClick={() => navigate("bizPartnersExplore")}
                className="shrink-0 w-[128px] rounded-[16px] bg-background-100 border border-background-200 p-3 flex flex-col items-center gap-2 cursor-pointer hover:border-background-300 transition-colors"
              >
                <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200">
                  <img src={p.logo} alt={p.name} className="w-full h-full object-cover object-top" />
                </div>
                <span className="text-[11.5px] font-medium text-foreground-800 text-center leading-tight">{p.name}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Products */}
      <div className="px-4 mt-6 pb-2">
        <div className="flex items-center justify-between gap-2 flex-wrap">
          <div className="flex items-center gap-2">
            <h2 className="text-[17px] font-semibold text-foreground-950">منتجات المنشأة</h2>
            <span className="text-[12px] text-foreground-500">{list.length} منتجات</span>
          </div>
          <OwnerLink icon="ri-upload-2-line" label="إدارة المنتجات ‹" onClick={() => navigate("bizProducts")} />
        </div>

        {list.length > 0 ? (
          <div className="grid grid-cols-2 gap-3 mt-3">
            {list.map((p) => (
              <BizOwnerProductCard key={p.id} product={p} />
            ))}
          </div>
        ) : (
          <div className="mt-3 rounded-[20px] border-2 border-dashed border-background-300 bg-background-100 p-5 flex flex-col items-center text-center gap-2.5">
            <span className="w-10 h-10 rounded-full bg-background-200 flex items-center justify-center">
              <i className="ri-shopping-bag-3-line text-[18px] text-foreground-600 leading-none" />
            </span>
            <p className="text-[13px] font-semibold text-foreground-800">لا توجد منتجات معروضة</p>
            <OwnerLink icon="ri-add-line" label="إضافة منتج ‹" onClick={() => navigate("bizProductForm")} />
          </div>
        )}
      </div>

      {/* Fixed bottom bar (owner-only) */}
      <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"
          onClick={() => navigate("bizEditData")}
          className="w-full h-[52px] rounded-[16px] bg-primary-500 text-background-50 text-[15px] font-semibold whitespace-nowrap cursor-pointer active:scale-[0.98] transition-transform flex items-center justify-center gap-2"
        >
          <i className="ri-pencil-line text-[17px] leading-none" />
          تعديل بيانات المنشأة
        </button>
      </div>
    </div>
  );
}