"use client";

import * as React from "react";
import Image from "next/image";
import {
  BadgeCheck,
  Trophy,
  ShieldCheck,
  ZoomIn,
  FileText,
} from "lucide-react";
import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
import { FadeIn } from "@/components/magicui/fade-in";
import { Lightbox } from "@/components/ui/lightbox";

type CertificationDetail = {
  id: string;
  name: string;
  category: string;
  description: string;
  issuer: string;
  scope: string;
  image: string;
};

type Credential = {
  id: string;
  name: string;
  category: string;
  image: string;
};

type Tab = "certifications" | "recognition";

/* ── Tab Button ──────────────────────────────────────── */
function TabButton({
  active,
  onClick,
  icon: Icon,
  label,
  count,
}: {
  active: boolean;
  onClick: () => void;
  icon: React.ElementType;
  label: string;
  count: number;
}) {
  return (
    <button
      onClick={onClick}
      className={cn(
        "relative flex items-center gap-2.5 rounded-full px-6 py-3 text-xs font-bold uppercase tracking-widest transition-all duration-300",
        active
          ? "bg-gold text-white shadow-md shadow-gold/30"
          : "border border-black/10 bg-white text-muted hover:border-gold/40 hover:text-gold"
      )}
    >
      <Icon className="h-3.5 w-3.5" />
      {label}
      <span
        className={cn(
          "ml-0.5 flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-bold",
          active ? "bg-white/20 text-white" : "bg-gold/10 text-gold"
        )}
      >
        {count}
      </span>
    </button>
  );
}

/* ── Certification Card (list layout) ───────────────── */
function CertCard({
  cert,
  index,
  onImageClick,
}: {
  cert: CertificationDetail;
  index: number;
  onImageClick: (src: string, alt: string) => void;
}) {
  const t = useTranslations("certPage");
  return (
    <FadeIn delay={index * 60}>
      <div className="group grid grid-cols-1 overflow-hidden rounded-2xl border border-black/5 bg-white shadow-sm transition-all duration-300 hover:-translate-y-1 hover:border-gold/15 hover:shadow-lg sm:grid-cols-[200px_1fr]">
        {/* Image panel */}
        <button
          onClick={() => onImageClick(cert.image, cert.name)}
          className="relative flex items-center justify-center overflow-hidden bg-gold-bg"
          aria-label={`View ${cert.name}`}
        >
          <div className="relative h-full min-h-[180px] w-full sm:min-h-[unset]">
            {cert.image.toLowerCase().endsWith(".pdf") ? (
              <div className="flex h-full w-full items-center justify-center text-gold/60">
                <FileText className="h-16 w-16 stroke-[1.5]" />
              </div>
            ) : (
              <Image
                src={cert.image}
                alt={cert.name}
                fill
                className="object-contain p-6 transition-transform duration-300 group-hover:scale-105"
                sizes="(max-width: 640px) 100vw, 200px"
              />
            )}
          </div>
          <div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors duration-300 group-hover:bg-black/8">
            <div className="flex h-9 w-9 items-center justify-center rounded-full opacity-0 shadow transition-all duration-300 group-hover:bg-white/90 group-hover:opacity-100 group-hover:text-gold">
              <ZoomIn className="h-4 w-4" />
            </div>
          </div>
        </button>

        {/* Content */}
        <div className="flex flex-col justify-center gap-2.5 p-6 sm:p-7">
          <span className="w-fit rounded-full bg-gold/10 px-3 py-1 text-[10px] font-bold uppercase tracking-widest text-gold">
            {cert.category}
          </span>
          <h2 className="font-serif text-lg font-bold text-ink sm:text-xl">{cert.name}</h2>
          <p className="text-xs leading-relaxed text-muted sm:text-sm">{cert.description}</p>
          <div className="mt-1 grid grid-cols-1 gap-2 border-t border-black/5 pt-3 sm:grid-cols-2">
            <div>
              <p className="text-[10px] font-bold uppercase tracking-wider text-muted">{t("issuedBy")}</p>
              <p className="mt-0.5 text-xs font-semibold text-ink">{cert.issuer}</p>
            </div>
            <div>
              <p className="text-[10px] font-bold uppercase tracking-wider text-muted">{t("scope")}</p>
              <p className="mt-0.5 text-xs font-semibold text-ink">{cert.scope}</p>
            </div>
          </div>
        </div>
      </div>
    </FadeIn>
  );
}

/* ── Credential Gallery Card (grid layout) ───────────── */
function CredentialCard({
  item,
  index,
  onImageClick,
}: {
  item: Credential;
  index: number;
  onImageClick: (index: number) => void;
}) {
  return (
    <FadeIn delay={index * 40}>
      <button
        onClick={() => onImageClick(index)}
        className="group relative w-full overflow-hidden rounded-2xl border border-black/5 bg-white shadow-sm transition-all duration-300 hover:-translate-y-1 hover:border-gold/20 hover:shadow-lg"
        aria-label={`View ${item.name}`}
      >
        {/* Image */}
        <div className="relative aspect-[4/3] w-full overflow-hidden bg-gold-bg">
          {item.image.toLowerCase().endsWith(".pdf") ? (
            <div className="flex h-full w-full items-center justify-center bg-gold/5 text-gold/60">
              <FileText className="h-20 w-20 stroke-[1.5]" />
            </div>
          ) : (
            <Image
              src={item.image}
              alt={item.name}
              fill
              className="object-contain p-6 transition-transform duration-300 group-hover:scale-105"
              sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
            />
          )}
          {/* Zoom overlay */}
          <div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors duration-300 group-hover:bg-black/10">
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-white/0 opacity-0 shadow-lg transition-all duration-300 group-hover:bg-white/95 group-hover:opacity-100">
              <ZoomIn className="h-4 w-4 text-gold" />
            </div>
          </div>
        </div>

        {/* Label */}
        <div className="border-t border-black/5 px-4 py-3 text-left">
          <p className="text-[10px] font-bold uppercase tracking-wider text-gold">
            {item.category}
          </p>
          <p className="mt-0.5 text-xs font-semibold text-ink leading-tight">
            {item.name}
          </p>
        </div>
      </button>
    </FadeIn>
  );
}

/* ── CertGallery (client island) ─────────────────────── */
export function CertGallery({
  certs,
  credentials,
}: {
  certs: CertificationDetail[];
  credentials: Credential[];
}) {
  const t = useTranslations("certPage");

  const [activeTab, setActiveTab] = React.useState<Tab>("certifications");

  // Cert list lightbox
  const [certLightbox, setCertLightbox] = React.useState<{
    src: string;
    alt: string;
  } | null>(null);

  // Gallery lightbox with index for prev/next
  const [galleryIndex, setGalleryIndex] = React.useState<number | null>(null);

  const openGallery = React.useCallback(
    (index: number) => setGalleryIndex(index),
    []
  );
  const closeGallery = React.useCallback(() => setGalleryIndex(null), []);
  const prevGallery = React.useCallback(
    () =>
      setGalleryIndex((i) => (i !== null && i > 0 ? i - 1 : i)),
    []
  );
  const nextGallery = React.useCallback(
    () =>
      setGalleryIndex((i) =>
        i !== null && i < credentials.length - 1 ? i + 1 : i
      ),
    [credentials.length]
  );

  return (
    <>
      {/* ── Cert list lightbox ───────────────────────────── */}
      {certLightbox && (
        <Lightbox
          src={certLightbox.src}
          alt={certLightbox.alt}
          onClose={() => setCertLightbox(null)}
        />
      )}

      {/* ── Gallery lightbox with navigation ────────────── */}
      {galleryIndex !== null && (
        <Lightbox
          src={credentials[galleryIndex].image}
          alt={credentials[galleryIndex].name}
          onClose={closeGallery}
          onPrev={prevGallery}
          onNext={nextGallery}
          hasPrev={galleryIndex > 0}
          hasNext={galleryIndex < credentials.length - 1}
        />
      )}

      {/* ── STICKY TAB BAR ───────────────────────────────── */}
      <div className="sticky top-[60px] z-40 border-b border-black/5 bg-white/95 py-3.5 backdrop-blur-sm">
        <div className="mx-auto max-w-[1400px] px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-center gap-3">
            <TabButton
              active={activeTab === "certifications"}
              onClick={() => setActiveTab("certifications")}
              icon={ShieldCheck}
              label={t("tabCerts")}
              count={certs.length}
            />
            <TabButton
              active={activeTab === "recognition"}
              onClick={() => setActiveTab("recognition")}
              icon={Trophy}
              label={t("tabRecognition")}
              count={credentials.length}
            />
          </div>
        </div>
      </div>

      {/* ── CONTENT ──────────────────────────────────────── */}
      <section className="bg-white py-12 sm:py-16">
        <div className="mx-auto max-w-6xl px-4 sm:px-6 lg:px-8">
          {/* ── CERTIFICATIONS — list layout ── */}
          {activeTab === "certifications" && (
            <div>
              <FadeIn>
                <div className="mb-10 flex flex-wrap items-center justify-center gap-2">
                  {certs.map((cert) => (
                    <div
                      key={cert.id}
                      className="flex items-center gap-1.5 rounded-full border border-gold/15 bg-gold-bg px-3.5 py-1.5 text-[11px] font-bold text-muted"
                    >
                      <BadgeCheck className="h-3 w-3 text-gold" />
                      {cert.name}
                    </div>
                  ))}
                </div>
              </FadeIn>
              <div className="space-y-5">
                {certs.map((cert, i) => (
                  <CertCard
                    key={cert.id}
                    cert={cert}
                    index={i}
                    onImageClick={(src, alt) =>
                      setCertLightbox({ src, alt })
                    }
                  />
                ))}
              </div>
            </div>
          )}

          {/* ── RECOGNITION — masonry grid gallery ── */}
          {activeTab === "recognition" && (
            <div>
              <FadeIn>
                <div className="mb-10 text-center">
                  <p className="text-xs font-bold uppercase tracking-[0.25em] text-gold">
                    {t("tabRecognition")}
                  </p>
                  <h2 className="mt-2 font-serif text-2xl font-bold text-ink sm:text-3xl">
                    {t("galleryTitle")}
                  </h2>
                  <p className="mx-auto mt-3 max-w-xl text-sm leading-relaxed text-muted">
                    {t("gallerySubtitle")}
                  </p>
                </div>
              </FadeIn>

              {/* Grid */}
              <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                {credentials.map((item, i) => (
                  <CredentialCard
                    key={item.id}
                    item={item}
                    index={i}
                    onImageClick={openGallery}
                  />
                ))}
              </div>

              {/* Counter */}
              <FadeIn>
                <p className="mt-8 text-center text-xs text-muted">
                  {t("showing")} {credentials.length} {t("credentials")}
                </p>
              </FadeIn>
            </div>
          )}
        </div>
      </section>
    </>
  );
}
