import { 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, Maximize, Share2 } from "lucide-react";
import { type ExpatStory } from "@/lib/expatContent";
import { getExpatStories } from "@/lib/webflowEvents";
import { resolveVideoEmbed } from "@/lib/videoEmbed";

type Props = { story: ExpatStory; moreStories: ExpatStory[] };

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

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

  const [copied, setCopied] = useState(false);

  const resolvedVideo = story.videoUrl
    ? resolveVideoEmbed(story.videoUrl)
    : null;

  const title = isEn ? story.title_en : story.title_mn;
  const body = isEn ? story.body_en : story.body_mn;
  const quote = isEn ? story.quote_en : story.quote_mn;
  const authorLine = byline(
    story.author,
    isEn ? story.location_en : story.location_mn,
  );

  const onShare = async () => {
    const url =
      typeof window !== "undefined"
        ? window.location.href
        : `https://send.mn/expat/stories/${story.slug}`;
    try {
      if (navigator.share) {
        await navigator.share({ title, url });
        return;
      }
      throw new Error("no-share-api");
    } catch {
      try {
        await navigator.clipboard.writeText(url);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      } catch {
        /* no-op */
      }
    }
  };

  return (
    <div className="relative min-h-screen overflow-x-hidden bg-black">
      <Head>
        <title>{`${title} | SendMN`}</title>
        <meta
          name="description"
          content={isEn ? story.excerpt_en : story.excerpt_mn}
        />
      </Head>

      <nav className="bg-white px-4 py-4 text-xs text-main sm:px-6 sm:text-sm lg:px-24">
        <Link
          href="/expat/stories"
          className="inline-flex items-center gap-1 text-main hover:text-main/70"
        >
          <ChevronLeft className="h-3.5 w-3.5" />
          {t("stories.breadcrumbCurrent")}
        </Link>
      </nav>

      <div className="relative h-[280px] w-full overflow-hidden bg-gradient-to-br from-[#12224f] via-[#1b3a86] to-[#00B6FF] sm:h-[420px] lg:h-[520px]">
        {resolvedVideo ? (
          // Locked to a real 16:9 box whose width is capped to whatever fits
          // the fixed hero height at each breakpoint (e.g. 280px tall -> at
          // most 498px wide), so the video is fully contained without ever
          // exceeding the hero's bounds, centered within any extra space.
          <div className="absolute inset-0 flex items-center justify-center overflow-hidden">
            {resolvedVideo.kind === "file" ? (
              <video
                src={resolvedVideo.src}
                className="aspect-video max-h-full w-[min(100%,498px)] sm:w-[min(100%,747px)] lg:w-[min(100%,924px)]"
                controls
                autoPlay
                poster={story.image}
              />
            ) : (
              <iframe
                src={resolvedVideo.src}
                title={title}
                className="aspect-video max-h-full w-[min(100%,498px)] border-0 sm:w-[min(100%,747px)] lg:w-[min(100%,924px)]"
                allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
                allowFullScreen
              />
            )}
          </div>
        ) : (
          <>
            {story.image && (
              <Image
                src={story.image}
                alt={title}
                fill
                className="object-cover"
                priority
              />
            )}
            <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/80 via-black/10 to-black/20" />

            <div className="absolute inset-x-0 bottom-0 px-4 pb-6 sm:px-6 sm:pb-8 lg:px-24">
              <h1 className="max-w-2xl text-2xl font-bold leading-snug text-white sm:text-3xl lg:text-4xl">
                {title}
              </h1>

              {story.videoDuration && (
                <div className="mt-4 flex items-center gap-3 text-[11px] text-white/70">
                  <span>0:00 / {story.videoDuration}</span>
                  <div className="h-0.5 flex-1 rounded-full bg-white/20">
                    <div className="h-0.5 w-0 rounded-full bg-white" />
                  </div>
                  <span className="font-semibold">HD</span>
                  <Maximize className="h-3.5 w-3.5" />
                </div>
              )}
            </div>
          </>
        )}
      </div>

      {/* Content */}
      <div className="bg-gradient-to-b from-[#eef9fb] to-white px-4 py-12 sm:px-6 sm:py-16 lg:px-24">
        <div className="mx-auto grid max-w-6xl grid-cols-1 gap-10 lg:grid-cols-[1.6fr_1fr]">
          <div>
            {story.category && (
              <span className="inline-block rounded-full border border-border bg-white px-3 py-1 text-xs font-semibold text-main">
                {story.category}
              </span>
            )}
            <h2 className="mt-3 text-2xl font-extrabold text-[#051973] sm:text-3xl">
              {title}
            </h2>
            {authorLine && (
              <p className="mt-2 text-sm font-medium text-sky-600">
                {authorLine}
              </p>
            )}

            <div className="mt-6 border-t border-border pt-6">
              <h3 className="text-sm font-bold uppercase tracking-wide text-main">
                {t("stories.detail.aboutTitle")}
              </h3>
              <div className="mt-3 space-y-4">
                {body.map((p, i) => (
                  <p key={i} className="text-sm text-gray-600 sm:text-base">
                    {p}
                  </p>
                ))}
              </div>
            </div>

            {quote && (
              <blockquote className="mt-6 border-l-4 border-[#051973] bg-white py-3 pl-5 pr-4 shadow-sm">
                <p className="text-sm italic text-gray-700 sm:text-base">
                  “{quote}”
                </p>
                {story.author && (
                  <footer className="mt-2 text-xs font-semibold text-main">
                    — {story.author}
                  </footer>
                )}
              </blockquote>
            )}

            <div className="mt-6 flex flex-wrap gap-2">
              {story.tags.map((tag) => (
                <span
                  key={tag}
                  className="rounded-full border border-border bg-white px-3 py-1 text-xs font-medium text-main"
                >
                  #{tag}
                </span>
              ))}
            </div>

            <button
              type="button"
              onClick={onShare}
              className="mt-8 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"
            >
              <Share2 className="h-4 w-4" />
              {copied
                ? t("stories.detail.shareCopied")
                : t("stories.detail.shareStory")}
            </button>
          </div>

          {moreStories.length > 0 && (
            <div>
              <h3 className="text-sm font-bold uppercase tracking-wide text-main">
                {t("stories.detail.moreStories")}
              </h3>
              <div className="mt-4 space-y-4">
                {moreStories.map((s) => (
                  <Link
                    key={s.slug}
                    href={`/expat/stories/${s.slug}`}
                    className="block rounded-2xl border border-border bg-white p-4 shadow-sm transition hover:shadow-md"
                  >
                    {s.category && (
                      <span className="inline-block rounded-full bg-bgBrand px-2.5 py-0.5 text-[11px] font-semibold text-main">
                        {s.category}
                      </span>
                    )}
                    <p className="mt-2 text-sm font-bold leading-snug text-[#051973]">
                      {isEn ? s.title_en : s.title_mn}
                    </p>
                    {s.author && (
                      <p className="mt-1 text-xs font-medium text-sky-600">
                        {s.author}
                      </p>
                    )}
                  </Link>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps<Props> = async ({
  params,
  locale,
}) => {
  const slug = String(params?.slug ?? "");
  const stories = await getExpatStories();
  const story = stories.find((s) => s.slug === slug);

  if (!story) {
    return { notFound: true };
  }

  const moreStories = stories.filter((s) => s.slug !== story.slug).slice(0, 3);

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