import { useMemo, useState, type ReactNode } from "react";
import { businesses, type Business } from "@/mocks/dshn";
import { useWeb } from "../WebContext";
import { WBtn, WCard, Container, cn, fmt } from "../WebUI";
import WebPageHeader from "../components/WebPageHeader";

const ACTIVITIES = [
  "أغذية ومشروبات",
  "إلكترونيات",
  "أزياء",
  "منتجات تجميل",
  "منتجات صناعية",
  "أثاث",
  "خدمات",
  "منتجات رقمية",
];
const CITIES = ["الرياض", "جدة", "الدمام"];
const VALUES = ["أقل من 1 مليون", "1 - 3 مليون", "أكثر من 3 مليون"];
const REVENUES = ["أقل من 3 مليون", "3 - 8 مليون", "أكثر من 8 مليون"];
const STAGES = ["فكرة", "تأسيس", "نمو", "توسع"];

interface BizFilterState {
  activity: string[];
  city: string[];
  value: string;
  revenue: string;
  stage: string[];
}

const EMPTY_FILTERS: BizFilterState = { activity: [], city: [], value: "", revenue: "", stage: [] };

const PIN_POS: Record<string, { x: number; y: number }> = {
  "biz-rim": { x: 46, y: 40 },
  "biz-tech": { x: 28, y: 58 },
  "biz-fashion": { x: 56, y: 30 },
  "biz-beauty": { x: 72, y: 62 },
  "biz-factory": { x: 78, y: 48 },
  "biz-furniture": { x: 38, y: 24 },
  "biz-services": { x: 22, y: 44 },
  "biz-digital": { x: 62, y: 44 },
};

export default function Businesses() {
  const { t, navigate } = useWeb();
  const [search, setSearch] = useState("");
  const [view, setView] = useState<"list" | "map">("list");
  const [filters, setFilters] = useState<BizFilterState>(EMPTY_FILTERS);
  const [activePin, setActivePin] = useState<Business | null>(null);

  const filtered = useMemo(() => {
    return businesses.filter((b) => {
      if (search && !b.name.includes(search) && !b.activity.includes(search)) return false;
      if (filters.activity.length > 0 && !filters.activity.includes(b.activity)) return false;
      if (filters.city.length > 0 && !filters.city.includes(b.city)) return false;
      if (filters.value === "أقل من 1 مليون" && b.estimatedValue >= 1000000) return false;
      if (filters.value === "1 - 3 مليون" && (b.estimatedValue < 1000000 || b.estimatedValue > 3000000)) return false;
      if (filters.value === "أكثر من 3 مليون" && b.estimatedValue <= 3000000) return false;
      if (filters.revenue === "أقل من 3 مليون" && b.annualSales >= 3000000) return false;
      if (filters.revenue === "3 - 8 مليون" && (b.annualSales < 3000000 || b.annualSales > 8000000)) return false;
      if (filters.revenue === "أكثر من 8 مليون" && b.annualSales <= 8000000) return false;
      if (filters.stage.length > 0 && !filters.stage.includes(b.stage)) return false;
      return true;
    });
  }, [search, filters]);

  const activeCount =
    filters.activity.length +
    filters.city.length +
    filters.stage.length +
    (filters.value ? 1 : 0) +
    (filters.revenue ? 1 : 0);

  const toggleArr = (key: "activity" | "city" | "stage", val: string) =>
    setFilters((f) => ({
      ...f,
      [key]: f[key].includes(val) ? f[key].filter((x) => x !== val) : [...f[key], val],
    }));

  const setRadio = (key: "value" | "revenue", val: string) =>
    setFilters((f) => ({ ...f, [key]: f[key] === val ? "" : val }));

  return (
    <div className="animate-fade-in">
      <WebPageHeader title={t("secBusinesses")} desc={`${filtered.length} ${t("results")}`} crumb={t("navBusinesses")} />

      <Container className="py-8">
        <div className="flex items-start gap-8">
          {/* sidebar filters (right in RTL) */}
          <aside className="w-[300px] shrink-0">
            <div className="flex items-center justify-between gap-3 mb-3.5">
              <h2 className="text-[17px] font-bold text-foreground-950 font-heading">الفلاتر</h2>
              {activeCount > 0 && (
                <button
                  type="button"
                  onClick={() => setFilters(EMPTY_FILTERS)}
                  className="text-[13px] font-semibold text-foreground-600 hover:text-foreground-950 cursor-pointer whitespace-nowrap"
                >
                  مسح الكل
                </button>
              )}
            </div>

            <div className="space-y-4">
              <FilterGroup title="النشاط">
                {ACTIVITIES.map((a) => (
                  <CheckRow
                    key={a}
                    label={a}
                    checked={filters.activity.includes(a)}
                    onClick={() => toggleArr("activity", a)}
                  />
                ))}
              </FilterGroup>

              <FilterGroup title="المدينة">
                {CITIES.map((c) => (
                  <CheckRow
                    key={c}
                    label={c}
                    checked={filters.city.includes(c)}
                    onClick={() => toggleArr("city", c)}
                  />
                ))}
              </FilterGroup>

              <FilterGroup title="القيمة">
                {VALUES.map((v) => (
                  <RadioRow
                    key={v}
                    label={v}
                    checked={filters.value === v}
                    onClick={() => setRadio("value", v)}
                  />
                ))}
              </FilterGroup>

              <FilterGroup title="حجم الإيرادات">
                {REVENUES.map((r) => (
                  <RadioRow
                    key={r}
                    label={r}
                    checked={filters.revenue === r}
                    onClick={() => setRadio("revenue", r)}
                  />
                ))}
              </FilterGroup>

              <FilterGroup title="مرحلة المشروع">
                {STAGES.map((s) => (
                  <CheckRow
                    key={s}
                    label={s}
                    checked={filters.stage.includes(s)}
                    onClick={() => toggleArr("stage", s)}
                  />
                ))}
              </FilterGroup>
            </div>
          </aside>

          {/* content */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-3">
              <div className="flex-1 flex items-center gap-2 h-12 px-4 rounded-[16px] bg-background-100 border border-background-200 focus-within:border-foreground-400 transition-colors">
                <i className="ri-search-line text-[19px] text-foreground-500 leading-none" />
                <input
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder="ابحث عن منشأة"
                  className="flex-1 bg-transparent text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
                />
              </div>
              <div className="flex bg-background-200 rounded-full p-1 shrink-0">
                <button
                  type="button"
                  onClick={() => setView("list")}
                  className={cn(
                    "h-10 px-5 rounded-full text-[13.5px] font-semibold cursor-pointer transition-colors flex items-center gap-1.5 whitespace-nowrap",
                    view === "list" ? "bg-primary-500 text-background-50" : "text-foreground-600",
                  )}
                >
                  <i className="ri-list-check text-[16px] leading-none" />
                  قائمة
                </button>
                <button
                  type="button"
                  onClick={() => setView("map")}
                  className={cn(
                    "h-10 px-5 rounded-full text-[13.5px] font-semibold cursor-pointer transition-colors flex items-center gap-1.5 whitespace-nowrap",
                    view === "map" ? "bg-primary-500 text-background-50" : "text-foreground-600",
                  )}
                >
                  <i className="ri-map-2-line text-[16px] leading-none" />
                  خريطة
                </button>
              </div>
            </div>

            <div className="mt-7">
              {view === "list" ? (
                filtered.length === 0 ? (
                  <WCard className="py-20 text-center">
                    <div className="w-16 h-16 rounded-full bg-background-200 flex items-center justify-center mx-auto mb-5">
                      <i className="ri-store-2-line text-[30px] text-foreground-500 leading-none" />
                    </div>
                    <p className="text-[15px] font-semibold text-foreground-950">لا توجد منشآت مطابقة</p>
                    <p className="text-[13px] text-foreground-600 mt-1.5">جرّب تعديل كلمة البحث أو الفلاتر.</p>
                  </WCard>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
                    {filtered.map((b) => (
                      <BusinessGridCard key={b.id} business={b} onClick={() => navigate("business", { businessId: b.id })} />
                    ))}
                  </div>
                )
              ) : (
                <div className="flex flex-col lg:flex-row gap-5">
                  <div className="w-full lg:w-[320px] shrink-0 space-y-3 lg:max-h-[620px] lg:overflow-y-auto">
                    {filtered.map((b) => (
                      <WCard
                        key={b.id}
                        className={cn("p-3.5 flex gap-3", activePin?.id === b.id && "border-foreground-400")}
                        onClick={() => setActivePin(b)}
                      >
                        <div
                          className="flex gap-3 w-full"
                          onMouseEnter={() => setActivePin(b)}
                        >
                          <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
                            <img src={b.logo} alt={b.name} className="w-full h-full object-cover object-top" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-[14px] font-semibold text-foreground-950">{b.name}</p>
                            <p className="text-[11.5px] text-foreground-600">{b.activity} • {b.city}</p>
                            <p className="text-[11.5px] text-foreground-600 mt-1">{fmt(b.estimatedValue)} ر.س</p>
                          </div>
                        </div>
                      </WCard>
                    ))}
                  </div>

                  <div className="flex-1 relative rounded-[20px] overflow-hidden border border-background-200 bg-background-100 min-h-[620px]">
                    <iframe
                      title="DSHN map"
                      src="https://www.google.com/maps?q=Riyadh,Saudi%20Arabia&z=6&output=embed"
                      className="w-full h-full absolute inset-0"
                      loading="lazy"
                    />
                    {filtered.map((b) => {
                      const pos = PIN_POS[b.id] ?? { x: 50, y: 50 };
                      return (
                        <button
                          key={b.id}
                          type="button"
                          onClick={() => setActivePin(b)}
                          style={{ left: `${pos.x}%`, top: `${pos.y}%` }}
                          className={cn(
                            "absolute -translate-x-1/2 -translate-y-1/2 w-9 h-9 rounded-full overflow-hidden border-2 cursor-pointer transition-transform hover:scale-110",
                            activePin?.id === b.id ? "border-primary-500 scale-110" : "border-background-50",
                          )}
                        >
                          <img src={b.logo} alt={b.name} className="w-full h-full object-cover object-top" />
                        </button>
                      );
                    })}
                    {activePin && (
                      <div className="absolute bottom-4 start-4 end-4 sm:end-auto sm:w-[340px] bg-background-50 rounded-[18px] border border-background-200 p-4">
                        <div className="flex items-center gap-3">
                          <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
                            <img src={activePin.logo} alt={activePin.name} className="w-full h-full object-cover object-top" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-[14.5px] font-semibold text-foreground-950">{activePin.name}</p>
                            <p className="text-[11.5px] text-foreground-600">{activePin.activity} • {activePin.city}</p>
                          </div>
                          <button type="button" onClick={() => setActivePin(null)} className="w-8 h-8 rounded-full hover:bg-background-200 flex items-center justify-center cursor-pointer shrink-0">
                            <i className="ri-close-line text-[17px] leading-none" />
                          </button>
                        </div>
                        <WBtn size="sm" className="w-full mt-3" onClick={() => navigate("business", { businessId: activePin.id })}>
                          عرض الصفحة
                        </WBtn>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </Container>
    </div>
  );
}

function FilterGroup({ title, children }: { title: string; children: ReactNode }) {
  return (
    <section className="rounded-[20px] bg-background-100 border border-background-200 p-4">
      <h3 className="text-[15px] font-semibold text-foreground-950 mb-1">{title}</h3>
      <div className="divide-y divide-background-200">{children}</div>
    </section>
  );
}

function CheckRow({ label, checked, onClick }: { label: string; checked: boolean; onClick: () => void }) {
  return (
    <button type="button" onClick={onClick} className="w-full min-h-[46px] flex items-center gap-3 py-2 cursor-pointer text-right">
      <span className={cn("flex-1 text-[13.5px] text-start", checked ? "font-semibold text-foreground-950" : "text-foreground-800")}>
        {label}
      </span>
      <span
        className={cn(
          "w-[22px] h-[22px] rounded-[7px] border flex items-center justify-center shrink-0 transition-colors",
          checked ? "bg-primary-500 border-primary-500" : "bg-background-50 border-background-300",
        )}
      >
        {checked && <i className="ri-check-line text-[15px] leading-none text-background-50" />}
      </span>
    </button>
  );
}

function RadioRow({ label, checked, onClick }: { label: string; checked: boolean; onClick: () => void }) {
  return (
    <button type="button" onClick={onClick} className="w-full min-h-[46px] flex items-center gap-3 py-2 cursor-pointer text-right">
      <span className={cn("flex-1 text-[13.5px] text-start", checked ? "font-semibold text-foreground-950" : "text-foreground-800")}>
        {label}
      </span>
      <span
        className={cn(
          "w-[22px] h-[22px] rounded-full border flex items-center justify-center shrink-0 transition-colors",
          checked ? "border-primary-500" : "border-background-300",
        )}
      >
        {checked && <span className="w-[12px] h-[12px] rounded-full bg-primary-500" />}
      </span>
    </button>
  );
}

function BusinessGridCard({ business, onClick }: { business: Business; onClick: () => void }) {
  return (
    <WCard className="p-5" onClick={onClick}>
      <div className="flex items-center gap-3">
        <span className="w-14 h-14 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" />
        </span>
        <div className="min-w-0">
          <div className="flex items-center gap-1.5">
            <h3 className="text-[15px] font-semibold text-foreground-950">{business.name}</h3>
            {business.verified && (
              <span className="inline-flex items-center gap-0.5 text-accent-700 text-[11px] font-semibold whitespace-nowrap">
                <i className="ri-verified-badge-fill text-[13px] leading-none" />
                موثّق
              </span>
            )}
          </div>
          <p className="text-[12px] text-foreground-600 mt-0.5">{business.activity} • {business.city}</p>
        </div>
      </div>

      <div className="mt-4 space-y-2">
        <div className="flex items-center justify-between gap-2 text-[12.5px]">
          <span className="text-foreground-600 whitespace-nowrap flex items-center gap-1" title="تقييم تقديري لقيمة المنشأة يُستخدم من المستثمرين لتقييم الفرصة">
            التقييم السوقي
            <i className="ri-information-line text-[11px] leading-none text-foreground-400" />
          </span>
          <span className="font-semibold text-foreground-900 whitespace-nowrap">{fmt(business.estimatedValue)} ر.س</span>
        </div>
        <div className="flex items-center justify-between gap-2 text-[12.5px]">
          <span className="text-foreground-600 whitespace-nowrap">حجم المبيعات</span>
          <span className="font-semibold text-foreground-900 whitespace-nowrap">{fmt(business.annualSales)} ر.س</span>
        </div>
      </div>

      {business.seekingInvest && (
        <div className="mt-4">
          <span className="inline-flex items-center gap-1 rounded-full bg-secondary-100 text-secondary-900 px-2.5 py-1 text-[11px] font-bold whitespace-nowrap">
            <i className="ri-seedling-line text-[12px] leading-none" />
            تبحث عن استثمار
          </span>
        </div>
      )}
    </WCard>
  );
}