"use client";

import Image from "next/image";
import Link from "next/link";
import { useMemo, useState } from "react";
import type { HomepageShowcaseSettings, Industry, Locale, Solution } from "@/types/content";
import { getImageAlt, getImageUrl } from "@/lib/images";
import { localizedPath } from "@/lib/routing";

type SectorItem = {
  label: string;
  title: string;
  body: string;
  href: string;
};

type HomeInteractiveShowcaseProps = {
  locale: Locale;
  sectorTitle: string;
  sectors: SectorItem[];
  solutionsTitle: string;
  solutionsBody: string;
  industries: Industry[];
  solutions: Solution[];
  showcase?: HomepageShowcaseSettings;
};

type ShowcaseMode = "industries" | "solutions";

export function HomeInteractiveShowcase({
  locale,
  sectorTitle,
  sectors,
  solutionsTitle,
  industries,
  solutions,
  showcase
}: HomeInteractiveShowcaseProps) {
  const [mode, setMode] = useState<ShowcaseMode>("industries");
  const [activeIndustry, setActiveIndustry] = useState(0);
  const [activeSolution, setActiveSolution] = useState(0);

  const industryItems = useMemo(
    () =>
      sectors.map((sector) => ({
        label: sector.label,
        title: sector.title,
        body: sector.body,
        href: localizedPath(sector.href, locale),
        cta: locale === "id" ? "Lihat sektor" : "Explore industry",
        image: getSectorShowcaseImage(sector, industries)
      })),
    [industries, locale, sectors]
  );

  const solutionItems = useMemo(
    () =>
      solutions.map((solution) => ({
        label: getSolutionEyebrow(solution, locale),
        title: solution.title[locale],
        body: solution.shortDescription[locale],
        href: localizedPath(`/solutions/${solution.slug}`, locale),
        cta: locale === "id" ? "Lihat solusi" : "Explore solution",
        image: solution.showcaseImage
      })),
    [locale, solutions]
  );

  const items = mode === "industries" ? industryItems : solutionItems;
  const activeIndex = mode === "industries" ? activeIndustry : activeSolution;
  const activeItem = items[activeIndex] ?? items[0];
  const setActiveIndex = mode === "industries" ? setActiveIndustry : setActiveSolution;
  const backgroundImage = getImageUrl(activeItem?.image) || getImageUrl(showcase?.backgroundImage);
  const backgroundVideo = showcase?.backgroundType === "video" ? showcase.backgroundVideo?.url : undefined;

  if (!activeItem) return null;

  const title = showcase?.title?.[locale] || (locale === "id" ? "Pilih sektor atau solusi yang paling relevan." : "Choose the right industry or solution.");
  const intro = showcase?.intro?.[locale] || (locale === "id" ? `${sectorTitle} dan ${solutionsTitle} dalam satu area eksplorasi yang lebih cepat.` : `${sectorTitle} and ${solutionsTitle} in one faster exploration area.`);
  const eyebrow = showcase?.eyebrow?.[locale] || (locale === "id" ? "Eksplorasi" : "Explore");

  return (
    <section className="home-showcase" aria-labelledby="home-showcase-title">
      <div className="home-showcase-header">
        <div>
          <p className="eyebrow">{eyebrow}</p>
          <h2 id="home-showcase-title">{title}</h2>
        </div>
        <p>{intro}</p>
      </div>

      <div className="home-showcase-shell">
        <aside className="home-showcase-sidebar" aria-label={locale === "id" ? "Pilih kategori homepage" : "Choose homepage category"}>
          <div className="home-showcase-mode">
            <button type="button" className={mode === "industries" ? "active" : ""} onClick={() => setMode("industries")}>
              {locale === "id" ? "Industri" : "Industry"}
            </button>
            <button type="button" className={mode === "solutions" ? "active" : ""} onClick={() => setMode("solutions")}>
              {locale === "id" ? "Solusi" : "Solutions"}
            </button>
          </div>

          <div className="home-showcase-list" role="tablist" aria-label={mode === "industries" ? sectorTitle : solutionsTitle}>
            {items.map((item, index) => (
              <button
                key={`${mode}-${item.href}`}
                type="button"
                className={index === activeIndex ? "active" : ""}
                role="tab"
                aria-selected={index === activeIndex}
                onClick={() => setActiveIndex(index)}
              >
                <span>{String(index + 1).padStart(2, "0")}</span>
                <strong>{item.label}</strong>
              </button>
            ))}
          </div>

          <Link className="home-showcase-all" href={localizedPath(mode === "industries" ? "/industries" : "/solutions", locale)}>
            {mode === "industries" ? (locale === "id" ? "Semua industri" : "All industries") : locale === "id" ? "Semua solusi" : "All solutions"} <span aria-hidden="true">›</span>
          </Link>
        </aside>

        <article className="home-showcase-card" key={`${mode}-${activeItem.href}`}>
          <div className="home-showcase-media" aria-hidden="true">
            {backgroundVideo ? (
              <video src={backgroundVideo} autoPlay muted loop playsInline preload="metadata" />
            ) : backgroundImage ? (
              <Image src={backgroundImage} alt={getImageAlt(activeItem.image || showcase?.backgroundImage, activeItem.title)} fill sizes="(max-width: 980px) 100vw, 70vw" quality={82} />
            ) : null}
          </div>
          <div className="home-showcase-card-overlay" aria-hidden="true" />
          <div className="home-showcase-card-copy">
            <p className="eyebrow">{activeItem.label}</p>
            <h3>{activeItem.title}</h3>
            <p>{activeItem.body}</p>
            <Link className="btn btn-primary" href={activeItem.href} aria-label={`${activeItem.cta}: ${activeItem.title}`}>
              {activeItem.cta}
            </Link>
          </div>
        </article>
      </div>
    </section>
  );
}

function getSectorShowcaseImage(sector: SectorItem, industries: Industry[]) {
  const slug = sector.href.split("/").filter(Boolean).at(-1);
  return industries.find((industry) => industry.slug === slug)?.showcaseImage;
}

function getSolutionEyebrow(item: Solution, locale: Locale) {
  const value = item.eyebrow?.[locale];
  if (!value || value === item.icon || value === "Solution" || value === "Solusi") return locale === "id" ? "Solusi" : "Solution";
  return value;
}
