import { useMemo, useState } from "react";
import Head from "next/head";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import type { GetServerSideProps } from "next";
import i18nConfig from "../../../../next-i18next.config";
import {
  ChevronLeft,
  Star,
  Play,
  ChevronDown,
  PenLine,
  Phone,
  Clapperboard,
} from "lucide-react";
import { type ExpatStory } from "@/lib/expatContent";
import { getExpatStories } from "@/lib/webflowEvents";
import ShareStoryForm from "@/components/expat/shareStoryForm";

const PAGE_SIZE = 6;

const steps = [
  { key: "step1", icon: PenLine },
  { key: "step2", icon: Phone },
  { key: "step3", icon: Clapperboard },
] as const;

// Joins whichever of author/location are actually present with " · ".
function byline(author?: string, location?: string): string {
  return [author, location].filter(Boolean).join(" · ");
}

type Props = { expatStories: ExpatStory[] };

export default function ExpatStoriesPage({ expatStories }: Props) {
  const router = useRouter();
  const { t, i18n } = useTranslation("expat");
  const lang = i18n.language || router.locale || "en";
  const isEn = lang === "en";

  const [activeCategory, setActiveCategory] = useState<string | "all">("all");
  const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);

  const featuredStory = expatStories.find((s) => s.featured) ?? expatStories[0];

  // Categories come straight from whatever each Webflow story was tagged
  // with — no fixed list, so the filter pills are just the distinct set
  // actually present.
  const categories = useMemo(
    () =>
      Array.from(new Set(expatStories.map((s) => s.category).filter(Boolean))),
    [expatStories],
  );

  const filteredStories = useMemo(
    () =>
      activeCategory === "all"
        ? expatStories
        : expatStories.filter((s) => s.category === activeCategory),
    [activeCategory, expatStories],
  );
  const visibleStories = filteredStories.slice(0, visibleCount);
  const hasMore = visibleCount < filteredStories.length;

  return (
    <div className="relative min-h-screen overflow-x-hidden bg-bgBrand">
      <Head>
        <title>{t("stories.meta.title")}</title>
        <meta name="description" content={t("stories.meta.description")} />
      </Head>

      {/* Hero */}
      <section className="relative overflow-hidden bg-gradient-to-br from-[#051973] via-[#0b3e98] to-[#00B6FF] px-4 pb-16 pt-8 sm:px-6 lg:px-24">
        <nav className="flex items-center gap-2 pt-6 text-xs text-white/70 sm:text-sm">
          <Link
            href="/expat"
            className="inline-flex items-center gap-1 hover:text-white"
          >
            <ChevronLeft className="h-3.5 w-3.5" />
            {t("events.breadcrumbHome")}
          </Link>
          <span>/</span>
          <span className="text-white">{t("stories.breadcrumbCurrent")}</span>
        </nav>

        <div className="relative mt-10 max-w-2xl pb-6 ml-0 sm:ml-12 lg:ml-24">
          <span className="inline-block rounded-full border border-white/30 bg-white/10 px-3 py-1 text-xs font-semibold text-white backdrop-blur">
            {t("stories.hero.badge")}
          </span>
          <h1 className="mt-4 text-3xl font-extrabold leading-tight text-white sm:text-4xl md:text-5xl">
            {t("stories.hero.title1")}
            <br />
            {t("stories.hero.title2")}
          </h1>
          <p className="mt-3 max-w-md text-sm text-white/80 sm:text-base">
            {t("stories.hero.subtitle")}
          </p>
        </div>
      </section>

      {/* This Week's Story */}
      <section className="bg-bgBrand px-4 py-16 sm:px-6 lg:px-24">
        <div className="mx-auto max-w-5xl">
          <span className="inline-block rounded-full border border-border bg-white px-3 py-1 text-xs font-semibold text-main">
            {t("stories.featured.badge")}
          </span>
          <h2 className="mt-3 text-2xl font-extrabold text-main sm:text-4xl">
            {t("stories.featured.title")}
          </h2>

          {featuredStory && (
            <article className="mt-8 grid grid-cols-1 overflow-hidden rounded-2xl bg-white shadow-xl lg:grid-cols-[1.1fr_1fr]">
              <div className="relative h-56 overflow-hidden bg-gradient-to-br from-[#374151] via-[#4b5563] to-[#9ca3af] lg:h-auto">
                {featuredStory.image && (
                  <Image
                    src={featuredStory.image}
                    alt={isEn ? featuredStory.title_en : featuredStory.title_mn}
                    fill
                    className="object-cover"
                    priority
                  />
                )}
              </div>

              <div className="flex flex-col justify-center p-6 sm:p-8">
                <span className="inline-flex w-fit items-center gap-1 rounded-full bg-[#051973] px-2.5 py-1 text-[11px] font-semibold text-white">
                  <Star className="h-3 w-3 fill-current" />
                  {t("stories.featured.badge")}
                </span>
                <h3 className="mt-3 text-xl font-bold text-[#051973] sm:text-2xl">
                  {isEn ? featuredStory.title_en : featuredStory.title_mn}
                </h3>
                {byline(
                  featuredStory.author,
                  isEn ? featuredStory.location_en : featuredStory.location_mn,
                ) && (
                  <p className="mt-1 text-sm font-medium text-sky-600">
                    {byline(
                      featuredStory.author,
                      isEn
                        ? featuredStory.location_en
                        : featuredStory.location_mn,
                    )}
                  </p>
                )}
                <p className="mt-3 text-sm text-gray-600 sm:text-base">
                  {isEn ? featuredStory.excerpt_en : featuredStory.excerpt_mn}
                </p>

                <div className="mt-6 flex items-center gap-3">
                  <Link
                    href={`/expat/stories/${featuredStory.slug}`}
                    className="inline-flex items-center justify-center gap-2 rounded-xl bg-[#051973] px-6 py-2.5 text-sm font-semibold text-white transition hover:brightness-110"
                  >
                    <Play className="h-3.5 w-3.5 fill-current" />
                    {t("stories.featured.watchStory")}
                  </Link>
                  {featuredStory.videoDuration && (
                    <span className="text-sm text-gray-400">
                      {featuredStory.videoDuration}
                    </span>
                  )}
                </div>
              </div>
            </article>
          )}
        </div>
      </section>

      {/* Explore Expat Stories */}
      <section className="bg-gradient-to-b from-[#eef9fb] to-white px-4 py-16 sm:px-6 lg:px-24">
        <div className="mx-auto max-w-6xl">
          <span className="inline-block rounded-full border border-border bg-white px-3 py-1 text-xs font-bold text-main">
            {t("stories.explore.badge")}
          </span>
          <h2 className="mt-3 text-2xl font-extrabold text-main sm:text-4xl">
            {t("stories.explore.title")}
          </h2>

          <div className="mt-6 flex flex-wrap gap-2">
            <button
              onClick={() => {
                setActiveCategory("all");
                setVisibleCount(PAGE_SIZE);
              }}
              className={`rounded-full px-4 py-2 text-sm font-semibold transition ${
                activeCategory === "all"
                  ? "bg-[#051973] text-white"
                  : "border border-border bg-white text-main hover:bg-blue-50"
              }`}
            >
              {t("stories.explore.all")}
            </button>
            {categories.map((cat) => (
              <button
                key={cat}
                onClick={() => {
                  setActiveCategory(cat);
                  setVisibleCount(PAGE_SIZE);
                }}
                className={`rounded-full px-4 py-2 text-sm font-semibold transition ${
                  activeCategory === cat
                    ? "bg-[#051973] text-white"
                    : "border border-border bg-white text-main hover:bg-blue-50"
                }`}
              >
                {cat}
              </button>
            ))}
          </div>

          <div className="mt-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {visibleStories.map((s) => (
              <Link
                key={s.slug}
                href={`/expat/stories/${s.slug}`}
                className="flex flex-col overflow-hidden rounded-2xl border border-border bg-white text-left shadow-sm transition hover:shadow-md"
              >
                <div className="relative h-40 overflow-hidden bg-gradient-to-br from-[#374151] via-[#6b7280] to-[#d1d5db]">
                  {s.image && (
                    <Image
                      src={s.image}
                      alt={isEn ? s.title_en : s.title_mn}
                      fill
                      className="object-cover"
                    />
                  )}
                </div>
                <div className="flex flex-1 flex-col p-5">
                  <h3 className="text-base font-bold leading-snug text-[#051973]">
                    {isEn ? s.title_en : s.title_mn}
                  </h3>
                  {byline(s.author, isEn ? s.location_en : s.location_mn) && (
                    <p className="mt-1 text-xs font-medium text-sky-600">
                      {byline(s.author, isEn ? s.location_en : s.location_mn)}
                    </p>
                  )}
                  <p className="mt-2 text-sm text-gray-600">
                    {isEn ? s.excerpt_en : s.excerpt_mn}
                  </p>
                  <span className="mt-auto inline-flex items-center gap-1 pt-4 text-xs font-semibold text-sky-600">
                    <Play className="h-3.5 w-3.5 fill-current" />
                    {t("stories.explore.watch")}
                  </span>
                </div>
              </Link>
            ))}
          </div>

          {filteredStories.length === 0 && (
            <p className="mt-10 text-center text-sm text-gray-500">
              {t("stories.explore.empty")}
            </p>
          )}

          {hasMore && (
            <div className="mt-10 flex justify-center">
              <button
                onClick={() => setVisibleCount((c) => c + PAGE_SIZE)}
                className="inline-flex items-center gap-2 rounded-xl border border-[#051973] px-5 py-2.5 text-sm font-semibold text-[#051973] transition hover:bg-blue-50"
              >
                {t("stories.explore.loadMore")}
                <ChevronDown className="h-4 w-4" />
              </button>
            </div>
          )}
        </div>
      </section>

      {/* Your Journey Matters */}
      <section className="bg-gradient-to-b from-[#eef9fb] to-white px-4 py-16 sm:px-6 lg:px-24">
        <div className="mx-auto max-w-6xl">
          <div className="text-center">
            <span className="inline-block rounded-full border border-border bg-white px-3 py-1 text-xs font-semibold text-main">
              {t("stories.journey.badge")}
            </span>
            <h2 className="mt-3 text-2xl font-extrabold text-main sm:text-4xl">
              {t("stories.journey.title")}
            </h2>
            <p className="mx-auto mt-3 max-w-2xl text-sm text-gray-600 sm:text-base">
              {t("stories.journey.desc")}
            </p>
          </div>

          <div className="mt-10 grid grid-cols-1 gap-6 sm:grid-cols-3">
            {steps.map(({ key, icon: Icon }, i) => (
              <div
                key={key}
                className="relative rounded-2xl border border-border bg-white p-6 shadow-sm"
              >
                <span className="absolute right-4 top-4 grid h-6 w-6 place-items-center rounded-full bg-[#051973] text-[11px] font-bold text-white">
                  {i + 1}
                </span>
                <div className="grid h-11 w-11 place-items-center rounded-xl bg-bgBrand text-[#051973]">
                  <Icon className="h-5 w-5" />
                </div>
                <h3 className="mt-4 text-sm font-bold text-main">
                  {t(`stories.journey.steps.${key}.title`)}
                </h3>
                <p className="mt-1 text-xs text-gray-600">
                  {t(`stories.journey.steps.${key}.desc`)}
                </p>
              </div>
            ))}
          </div>

          <div className="mt-14 grid grid-cols-1 gap-10 lg:grid-cols-2">
            <div>
              {/* <h3 className="text-lg font-bold text-main sm:text-xl">
                {t("stories.journey.readyTitle")}
              </h3>
              <p className="mt-2 text-sm text-gray-600">
                {t("stories.journey.readyDesc")}
              </p> */}
              {/* 
              <blockquote className="mt-6 rounded-2xl border border-border bg-white p-5 shadow-sm">
                <p className="text-sm italic text-gray-600">
                  {t("stories.journey.quote")}
                </p>
                <footer className="mt-3 flex items-center gap-3">
                  <div className="grid h-8 w-8 place-items-center rounded-full bg-bgBrand text-xs font-bold text-main">
                    MV
                  </div>
                  <div className="text-xs">
                    <p className="font-semibold text-main">
                      {t("stories.journey.quoteAuthor")}
                    </p>
                    <p className="text-gray-500">
                      {t("stories.journey.quoteFrom")}
                    </p>
                  </div>
                </footer>
              </blockquote> */}
            </div>

            <ShareStoryForm />
          </div>
        </div>
      </section>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps<Props> = async ({
  locale,
}) => {
  const expatStories = await getExpatStories();

  return {
    props: {
      expatStories,
      ...(await serverSideTranslations(
        locale ?? "en",
        ["common", "expat"],
        i18nConfig,
      )),
    },
  };
};
