import { useEffect, useState } from "react";
import { useApp } from "../AppContext";
import {
  banners,
  businesses,
  categories,
  opportunities,
  opportunityCategories,
  type Banner,
} from "@/mocks/dshn";
import { products } from "@/mocks/dshnCommerce";
import { BusinessMini } from "../components/BusinessCard";
import ProductCard from "../components/ProductCard";
import NewsTicker from "../components/NewsTicker";
import AutoMarquee from "@/components/feature/AutoMarquee";
import { Chip, SectionHeader, cn } from "../components/ui";

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

function SectionEmpty() {
  return (
    <div className="mx-4 mt-3 rounded-[20px] bg-background-100 border border-background-200 py-8 flex flex-col items-center gap-2">
      <i className="ri-inbox-line text-[26px] text-foreground-400 leading-none" />
      <p className="text-[13px] text-foreground-600">لا توجد نتائج حاليًا</p>
    </div>
  );
}

function BannerCarousel() {
  const { navigate } = useApp();
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const t = setInterval(() => setIndex((i) => (i + 1) % banners.length), 4500);
    return () => clearInterval(t);
  }, []);

  const open = (b: Banner) => {
    if (b.action === "business") navigate("business", { businessId: b.refId });
    else if (b.action === "product") navigate("product", { productId: b.refId });
    else navigate("products", { categoryId: b.refId });
  };

  return (
    <div className="px-4">
      <div
        dir="ltr"
        className="relative w-full h-[180px] rounded-[20px] overflow-hidden bg-background-200"
      >
        <div
          className="flex h-full transition-transform duration-500 ease-out"
          style={{ transform: `translateX(-${index * 100}%)` }}
        >
          {banners.map((b) => (
            <button
              key={b.id}
              type="button"
              dir="rtl"
              onClick={() => open(b)}
              className="relative w-full h-full shrink-0 text-start cursor-pointer"
            >
              <img src={b.image} alt={b.title} className="w-full h-full object-cover object-top" />
              <div className="absolute inset-0 bg-gradient-to-l from-foreground-950/80 via-foreground-950/45 to-foreground-950/5" />
              <div className="absolute inset-0 p-5 flex flex-col justify-center">
                <span className="self-start rounded-full bg-secondary-500 text-secondary-950 text-[10.5px] font-bold px-2.5 py-1 mb-2">
                  {b.tag}
                </span>
                <h3 className="text-[19px] font-bold text-background-50 leading-snug max-w-[72%]">
                  {b.title}
                </h3>
                <p className="text-[12.5px] text-background-50/90 mt-1 max-w-[72%]">{b.subtitle}</p>
              </div>
            </button>
          ))}
        </div>
      </div>
      <div className="flex items-center justify-center gap-1.5 mt-3">
        {banners.map((b, i) => (
          <button
            key={b.id}
            type="button"
            aria-label={`الشريحة ${i + 1}`}
            onClick={() => setIndex(i)}
            className={cn(
              "h-1.5 rounded-full transition-all cursor-pointer",
              i === index ? "w-5 bg-foreground-950" : "w-1.5 bg-background-300",
            )}
          />
        ))}
      </div>
    </div>
  );
}

function CategoryCircles() {
  const { navigate } = useApp();
  return (
    <div className="flex gap-4 overflow-x-auto no-scrollbar px-4 pb-1">
      {categories.map((c) => (
        <button
          key={c.id}
          type="button"
          onClick={() => navigate("products", { categoryId: c.id })}
          className="shrink-0 flex flex-col items-center gap-2 w-[80px] cursor-pointer"
        >
          <span className="w-[72px] h-[72px] rounded-full overflow-hidden bg-background-100 border border-background-200">
            <img src={c.image} alt={c.name} className="w-full h-full object-cover object-top" />
          </span>
          <span className="text-[12.5px] text-foreground-700 text-center leading-tight line-clamp-2">
            {c.name}
          </span>
        </button>
      ))}
    </div>
  );
}

function Opportunities() {
  const { navigate } = useApp();
  const cats = opportunityCategories;
  const [cat, setCat] = useState(cats[0]);

  const cards = opportunities
    .filter((o) => o.category === cat)
    .map((o) => ({ o, biz: businesses.find((b) => b.id === o.businessId) }))
    .filter((x): x is { o: typeof opportunities[number]; biz: typeof businesses[number] } => Boolean(x.biz));

  return (
    <div>
      <SectionHeader
        title="العروض والفرص"
        actionLabel="عرض الكل"
        onAction={() => navigate("businesses")}
        className="px-4"
      />
      <div className="flex gap-2 overflow-x-auto no-scrollbar px-4 mt-3">
        {cats.map((c) => (
          <Chip key={c} active={c === cat} onClick={() => setCat(c)}>
            {c}
          </Chip>
        ))}
      </div>

      {cards.length === 0 ? (
        <SectionEmpty />
      ) : (
        <AutoMarquee className="mt-3" speed={52}>
          {cards.map(({ o, biz }) => (
            <button
              key={o.id}
              type="button"
              onClick={() => navigate("business", { businessId: biz.id })}
              className="shrink-0 w-[280px] text-start rounded-[20px] bg-background-100 border border-background-200 p-4 cursor-pointer hover:border-background-300 transition-colors"
            >
              <div className="flex items-center gap-3">
                <span className="w-11 h-11 rounded-full overflow-hidden bg-background-200 shrink-0">
                  <img src={biz.logo} alt={biz.name} className="w-full h-full object-cover object-top" />
                </span>
                <div className="min-w-0">
                  <h3 className="text-[14.5px] font-semibold text-foreground-950 truncate">{biz.name}</h3>
                  <p className="text-[11.5px] text-foreground-600 flex items-center gap-1">
                    <i className="ri-star-fill text-secondary-500 text-[11px] leading-none" />
                    {biz.rating}
                  </p>
                </div>
              </div>
              <div className="mt-3 pt-3 border-t border-background-200 flex items-center justify-between gap-3">
                <div>
                  <p className="text-[10.5px] text-foreground-600">قيمة الاستثمار</p>
                  <p className="text-[14px] font-bold text-foreground-950 mt-0.5">
                    {fmt(o.requiredInvestment)} ر.س
                  </p>
                </div>
                <div className="rounded-[12px] bg-accent-100 px-3 py-1.5 text-center shrink-0">
                  <p className="text-[10px] font-semibold text-accent-800">النسبة المعروضة</p>
                  <p className="text-[15px] font-bold text-accent-900 leading-tight">{o.equity}%</p>
                </div>
              </div>
            </button>
          ))}
        </AutoMarquee>
      )}
    </div>
  );
}

function BusinessStrip() {
  const { navigate } = useApp();
  const list = businesses.slice(0, 6);

  return (
    <div>
      <SectionHeader
        title="المنشآت"
        actionLabel="عرض الكل"
        onAction={() => navigate("businesses")}
        className="px-4"
      />
      {list.length === 0 ? (
        <SectionEmpty />
      ) : (
        <AutoMarquee className="mt-3" speed={56}>
          {list.map((b) => (
            <BusinessMini
              key={b.id}
              business={b}
              width="w-[280px]"
              onClick={() => navigate("business", { businessId: b.id })}
            />
          ))}
        </AutoMarquee>
      )}
    </div>
  );
}

function ProductSection() {
  const { navigate } = useApp();
  const list = products.slice(0, 6);

  return (
    <div>
      <SectionHeader
        title="المنتجات"
        actionLabel="عرض الكل"
        onAction={() => navigate("products")}
        className="px-4"
      />
      {list.length === 0 ? (
        <SectionEmpty />
      ) : (
        <div data-product-shop className="grid grid-cols-2 gap-3 px-4 mt-3 pb-1">
          {list.map((p) => (
            <ProductCard
              key={p.id}
              product={p}
              onClick={() => navigate("product", { productId: p.id })}
              onClickBusiness={() => navigate("business", { businessId: p.businessId })}
            />
          ))}
        </div>
      )}
    </div>
  );
}

export default function Home() {
  return (
    <div className="pb-8">
      <NewsTicker />

      <div className="pt-4 space-y-6">
        <BannerCarousel />
        <CategoryCircles />
        <ProductSection />
        <Opportunities />
        <BusinessStrip />
      </div>
    </div>
  );
}