"use client";

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

type HomeSolutionsShowcaseProps = {
  locale: Locale;
  solutions: Solution[];
  showcase?: HomepageShowcaseSettings;
};

export function HomeSolutionsShowcase({ locale, solutions, showcase }: HomeSolutionsShowcaseProps) {
  const curated = useMemo(() => {
    const slugs = showcase?.items ?? [];
    if (!slugs.length) return solutions;
    const bySlug = new Map(solutions.map((item) => [item.slug, item]));
    const ordered = slugs.map((slug) => bySlug.get(slug)).filter((item): item is Solution => Boolean(item));
    return ordered.length ? ordered : solutions;
  }, [showcase?.items, solutions]);

  const items = useMemo(
    () =>
      curated.map((item) => ({
        label: getSolutionShortLabel(item.slug, item.title[locale], locale),
        title: item.title[locale],
        eyebrow: item.eyebrow?.[locale] ?? "Solution",
        body: item.shortDescription[locale],
        href: `/solutions/${item.slug}`,
        image: item.showcaseImage ?? item.heroImage
      })),
    [locale, curated]
  );

  const [activeIndex, setActiveIndex] = useState(0);
  const activeItem = items[activeIndex] ?? items[0];

  if (!activeItem) return null;

  // The stage background is the active solution's own showcase (or hero) image.
  const activeImage = getImageUrl(activeItem.image);
  const eyebrow = showcase?.eyebrow?.[locale] || (locale === "id" ? "Solusi" : "Solutions");

  return (
    <section className="home-solutions-showcase" aria-labelledby="home-solutions-title">
      <article className="home-solutions-stage" key={activeItem.href}>
        <div className="home-solutions-media" aria-hidden="true">
          {activeImage ? (
            <Image src={activeImage} alt={getImageAlt(activeItem.image, activeItem.title)} fill sizes="100vw" />
          ) : null}
        </div>
        <div className="home-solutions-overlay" aria-hidden="true" />
        <div className="home-solutions-tabs-wrap">
          <div className="home-solutions-list" role="tablist" aria-label={eyebrow}>
            {items.map((item, index) => (
              <button
                key={item.href}
                type="button"
                className={index === activeIndex ? "active" : ""}
                aria-pressed={index === activeIndex}
                onMouseEnter={() => setActiveIndex(index)}
                onFocus={() => setActiveIndex(index)}
              >
                <span>{String(index + 1).padStart(2, "0")}</span>
                {item.label}
              </button>
            ))}
          </div>
        </div>
        <label className="home-solutions-mobile-picker">
          <span>{locale === "id" ? "Pilih solusi" : "Choose solution"}</span>
          <select
            aria-label={locale === "id" ? "Pilih solusi" : "Choose solution"}
            value={String(activeIndex)}
            onChange={(event) => setActiveIndex(Number(event.target.value))}
          >
            {items.map((item, index) => (
              <option key={item.href} value={String(index)}>
                {String(index + 1).padStart(2, "0")} - {item.label}
              </option>
            ))}
          </select>
        </label>
        <div className="home-solutions-copy">
          <h2 id="home-solutions-title">{activeItem.title}</h2>
          <p>{activeItem.body}</p>
          <div className="home-solutions-actions">
            <Link className="home-solutions-all" prefetch={false} href={localizedPath(activeItem.href, locale)}>
              {locale === "id" ? "Jelajahi" : "Explore"} <span aria-hidden="true">›</span>
            </Link>
          </div>
        </div>
      </article>
    </section>
  );
}

function getSolutionShortLabel(slug: string, fallback: string, locale: Locale) {
  const labels: Record<string, { en: string; id: string }> = {
    "command-center": { en: "Command Center", id: "Command Center" },
    "digital-signage": { en: "Digital Signage", id: "Digital Signage" },
    "immersive-room": { en: "Immersive", id: "Immersive" },
    "led-display-videotron": { en: "LED Display", id: "LED Display" },
    "meeting-room-video-conference": { en: "Meeting Room", id: "Meeting Room" },
    "professional-audio-system": { en: "Pro Audio", id: "Pro Audio" },
    "smart-classroom": { en: "Smart Classroom", id: "Smart Classroom" }
  };

  return labels[slug]?.[locale] ?? fallback;
}
