import { ChevronRight } from "lucide-react";
import { Link } from "react-router-dom";
import { useEffect, useRef, useState } from "react";
import { getJSON, itemsOrEmpty, type Category, type Resource } from "../api";
import { CategoryIcon } from "../components/CategoryIcon";
import { FigmaBanner } from "../components/FigmaBanner";
import {
  ComingSoonLatestUpdateRow,
  LatestUpdateRow,
} from "../components/LatestUpdateRow";
import {
  ComingSoonRecommendedCard,
  RecommendedCard,
} from "../components/RecommendedCard";
import { SectionHeader } from "../components/SectionHeader";
import { useI18n } from "../i18n";
import { categoryCardLines } from "../utils/categoryDisplay";

export function Home() {
  const { t, lang } = useI18n();
  const [cats, setCats] = useState<Category[]>([]);
  const [rec, setRec] = useState<Resource[]>([]);
  const [latest, setLatest] = useState<Resource[]>([]);
  const [err, setErr] = useState<string | null>(null);
  const recRowRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const q = `?lang=${encodeURIComponent(lang)}`;
    Promise.all([
      getJSON<Category[]>(`/api/categories${q}`),
      getJSON<{ items: Resource[] }>(`/api/resources/recommended${q}&limit=12`),
      getJSON<{ items: Resource[] }>(`/api/resources/latest${q}&limit=8`),
    ])
      .then(([c, r, l]) => {
        setCats(itemsOrEmpty(c));
        setRec(itemsOrEmpty(r.items));
        setLatest(itemsOrEmpty(l.items));
      })
      .catch((e) => setErr(String(e)));
  }, [lang]);

  const iconKeyForResource = (r: Resource) =>
    cats.find((c) => c.id === r.categoryId)?.iconKey ?? "folder";

  const scrollRec = (dir: 1 | -1) => {
    recRowRef.current?.scrollBy({ left: dir * 280, behavior: "smooth" });
  };

  const recommendedPlaceholderCount = Math.max(0, 5 - rec.length);
  const latestPlaceholderCount = Math.max(0, 5 - latest.length);

  if (err) {
    return (
      <div className="mt-6 rounded-xl border border-red-900 bg-red-950/40 p-4 text-red-200 md:mt-0">
        {err}
      </div>
    );
  }

  return (
    <div className="space-y-[30px] pb-10 md:space-y-10 md:pb-16 xl:space-y-[34px]">
      <section className="-mt-6 md:mt-0">
        <FigmaBanner />
      </section>

      <section id="categories" className="scroll-mt-24">
        <SectionHeader
          title={t("categorySection")}
          viewAllTo="/browse"
          viewAllLabel={t("viewAll")}
        />
        <div className="mt-7 grid grid-cols-3 gap-3 min-[440px]:gap-3.5 md:grid-cols-5 md:gap-3 lg:grid-cols-6 xl:grid-cols-7 xl:gap-4">
          {cats.map((c) => {
            const { line1, line2 } = categoryCardLines(c.name);
            return (
              <Link
                key={c.id}
                to={`/category/${c.slug}`}
                className="group flex min-h-[111px] min-w-0 flex-col items-center justify-center gap-3 rounded-xl border border-ark-line bg-ark-panel px-2.5 py-4 text-center transition hover:border-ark-gold/55 hover:shadow-[0_0_0_1px_rgba(238,183,38,0.12)] md:min-h-24 md:flex-row md:justify-start md:gap-4 md:px-5 md:text-left"
              >
                <CategoryIcon
                  iconKey={c.iconKey}
                  categorySlug={c.slug}
                  className="h-9 w-9 shrink-0 text-ark-gold md:h-9 md:w-9"
                />
                <div className="min-w-0">
                  <div className="text-[15px] font-bold leading-snug text-white line-clamp-2 md:text-sm">
                    {line1}
                  </div>
                  {line2 ? (
                    <div className="mt-0.5 text-[15px] font-bold leading-snug text-white line-clamp-2 md:text-sm">
                      {line2}
                    </div>
                  ) : null}
                </div>
              </Link>
            );
          })}
        </div>
      </section>

      <section>
        <SectionHeader
          title={t("officialSection")}
          viewAllTo="/browse?sort=recommended"
          viewAllLabel={t("viewAll")}
        />
        <div className="relative mt-7">
          <div
            ref={recRowRef}
            className="flex gap-3 overflow-x-auto pb-5 pr-0 scroll-smooth snap-x snap-mandatory [-ms-overflow-style:none] [scrollbar-width:none] md:gap-4 [&::-webkit-scrollbar]:hidden"
          >
            {rec.map((r, index) => (
              <div key={r.id} className="snap-start">
                <RecommendedCard r={r} visualIndex={index} />
              </div>
            ))}
            {Array.from({ length: recommendedPlaceholderCount }).map(
              (_, index) => (
                <div
                  key={`recommended-coming-soon-${index}`}
                  className="snap-start"
                >
                  <ComingSoonRecommendedCard visualIndex={rec.length + index} />
                </div>
              ),
            )}
          </div>
          <div className="h-1 rounded-full bg-black/80 md:hidden">
            <div className="h-full w-24 rounded-full bg-[#353740]" />
          </div>
          <button
            type="button"
            onClick={() => scrollRec(1)}
            className="absolute right-0 top-[45%] hidden h-9 w-9 -translate-y-1/2 items-center justify-center rounded-lg border border-ark-line bg-[#292a31]/95 text-neutral-200 shadow-lg backdrop-blur transition hover:border-ark-gold hover:text-ark-gold md:flex"
            aria-label={t("viewAll")}
          >
            <ChevronRight className="h-5 w-5" />
          </button>
        </div>
      </section>

      <section>
        <SectionHeader
          title={t("latestSection")}
          viewAllTo="/browse?sort=latest"
          viewAllLabel={t("viewAll")}
        />
        <div className="mt-7 grid gap-3 min-[576px]:grid-cols-2 md:gap-4 lg:grid-cols-3 xl:grid-cols-5">
          {latest.map((r) => (
            <LatestUpdateRow key={r.id} r={r} iconKey={iconKeyForResource(r)} />
          ))}
          {Array.from({ length: latestPlaceholderCount }).map((_, index) => (
            <ComingSoonLatestUpdateRow
              key={`latest-coming-soon-${index}`}
              index={latest.length + index}
            />
          ))}
        </div>
      </section>
    </div>
  );
}
