"use client";

import { getStorageUrl } from "@/lib/utils";

interface GalleryImage {
  image?: string | null;
  name?: string | null;
  description?: string | null;
}

interface PackageGalleryProps {
  bannerImage: string | null;
  packageName: string;
  images: GalleryImage[];
  /** Optional: discount badge, premium badge, etc. */
  badges?: React.ReactNode;
  /** Optional: class for the main card */
  className?: string;
}

const placeholderSvg = (label: string) =>
  `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300' viewBox='0 0 400 300'%3E%3Crect fill='%23e2e8f0' width='400' height='300'/%3E%3Ctext fill='%2394a3b8' x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' font-family='sans-serif' font-size='16'%3E${encodeURIComponent(label)}%3C/text%3E%3C/svg%3E`;

/**
 * Renders a single gallery cell (image or placeholder).
 */
export function GalleryCell({
  img,
  index,
  total,
  useStackedLayout35,
  gridClass: _gridClass,
}: {
  img: GalleryImage;
  index: number;
  total: number;
  useStackedLayout35: boolean;
  gridClass: string;
}) {
  const rawUrl = img.image ?? "";
  const src = !rawUrl
    ? placeholderSvg(`View ${index + 1}`)
    : rawUrl.startsWith("http://") || rawUrl.startsWith("https://")
      ? rawUrl
      : getStorageUrl(rawUrl) || rawUrl;
  const isFifthOfFive = !useStackedLayout35 && total === 5 && index === 4;

  return (
    <div
      className={`relative min-h-0 h-full w-full rounded-xl overflow-hidden bg-muted group ${
        isFifthOfFive ? "lg:col-span-2" : ""
      }`}
    >
      <img
        src={src}
        alt={img.name || `Gallery ${index + 1}`}
        className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
        loading="lazy"
        onError={(e) => {
          const t = e.currentTarget;
          if (!t.dataset.fallback) {
            t.dataset.fallback = "1";
            t.src = placeholderSvg(`View ${index + 1}`);
          }
        }}
      />
    </div>
  );
}

/**
 * Package image gallery: banner + optional grid of extra images.
 */
export function PackageGallery({
  bannerImage,
  packageName,
  images,
  badges,
  className,
}: PackageGalleryProps) {
  const displayImages = images.slice(0, 6);
  const galleryCount = displayImages.length;
  const useStackedLayout35 = galleryCount === 3 || galleryCount === 5;
  const gridClass =
    galleryCount <= 1
      ? "grid-cols-1 grid-rows-1"
      : galleryCount === 2
        ? "grid-cols-1 grid-rows-2"
        : galleryCount === 4
          ? "grid-cols-2 grid-rows-2"
          : "grid-cols-2 grid-rows-3";
  const galleryRowCols =
    galleryCount === 3
      ? "grid-cols-3"
      : galleryCount === 5
        ? "grid-cols-5"
        : null;

  const bannerSrc = bannerImage
    ? bannerImage.startsWith("http")
      ? bannerImage
      : getStorageUrl(bannerImage)
    : null;

  const bannerBlock = (
    <div className="relative w-full min-h-[280px] md:min-h-[360px] rounded-xl overflow-hidden bg-gradient-to-br from-purple-100 to-blue-100">
      {bannerSrc ? (
        <img
          src={bannerSrc}
          alt={packageName}
          className="w-full h-full min-h-[280px] md:min-h-[360px] object-cover transition-transform duration-300 hover:scale-[1.02]"
        />
      ) : (
        <div className="absolute inset-0 flex items-center justify-center">
          <span className="text-4xl text-purple-300" aria-hidden>
            ✨
          </span>
        </div>
      )}
      {badges && (
        <div className="absolute top-3 left-3 flex flex-wrap gap-2">
          {badges}
        </div>
      )}
    </div>
  );

  if (galleryCount === 0) {
    return (
      <div className={className}>
        <div className="p-4 pt-2 md:p-6 md:pt-2">{bannerBlock}</div>
      </div>
    );
  }

  if (useStackedLayout35) {
    return (
      <div className={className}>
        <div className="grid grid-rows-[5fr_2fr] min-h-[280px] md:min-h-[340px] gap-2 p-4 pt-2 md:p-6 md:pt-2">
          {bannerBlock}
          <div className={`grid ${galleryRowCols} gap-2 min-h-0 h-full w-full`}>
            {displayImages.map((img, idx) => (
              <GalleryCell
                key={idx}
                img={img}
                index={idx}
                total={displayImages.length}
                useStackedLayout35={useStackedLayout35}
                gridClass={gridClass}
              />
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={className}>
      <div className="grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-2 p-4 pt-2 md:p-6 md:pt-2 items-stretch">
        {bannerBlock}
        <div
          className={`grid gap-2 min-h-[280px] lg:min-h-[360px] h-full ${gridClass}`}
        >
          {displayImages.map((img, idx) => (
            <GalleryCell
              key={idx}
              img={img}
              index={idx}
              total={displayImages.length}
              useStackedLayout35={false}
              gridClass={gridClass}
            />
          ))}
        </div>
      </div>
    </div>
  );
}
