import { useMemo, useState, useEffect } from "react"
import type { DealImage } from "../../models/deal/DealImage"

type DealImagesProps = {
  images: DealImage[]
  alt?: string
  isExpired?: boolean
}

export default function DealImages({ images, alt, isExpired = false }: DealImagesProps) {
  const srcs = useMemo(() => {
    return (images ?? [])
      .filter((x) => x?.imageUrl && x.imageUrl.trim().length > 0)
      .sort((a, b) => a.order - b.order)
      .slice(0, 5)
      .map((x) => x.imageUrl.trim())
  }, [images])

  const [activeIndex, setActiveIndex] = useState(0)
  const [imgError, setImgError] = useState(false)

  useEffect(() => {
    setActiveIndex(0)
    setImgError(false)
  }, [srcs.length])

  if (srcs.length === 0) {
    return (
      <div className="w-full">
        <div className="rounded-3xl bg-background border border-white/10 overflow-hidden">
          <div className="relative w-full aspect-[4/3] bg-surface">
            <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
              <div className="w-12 h-12 rounded-2xl bg-surface border border-white/10 flex items-center justify-center text-text">
                🖼️
              </div>
              <div className="text-sm font-semibold text-text">Görsel yok</div>
            </div>
          </div>
        </div>
      </div>
    )
  }

  const safeIndex = Math.min(activeIndex, srcs.length - 1)
  const activeSrc = srcs[safeIndex]

  const expiredClass = isExpired ? "grayscale opacity-90" : ""

  return (
    <div className="w-full">
      {/* Main image */}
      <div className="rounded-t-2xl bg-background overflow-hidden">
        <div className="relative w-full aspect-[4/3] bg-surface">
          {!imgError ? (
            <img
              src={activeSrc}
              alt={alt ?? "deal image"}
              className={[
                "absolute inset-0 w-full h-full object-contain transition",
                expiredClass,
              ].join(" ")}
              onError={() => setImgError(true)}
            />
          ) : (
            <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
              <div className="w-12 h-12 rounded-2xl bg-surface border border-white/10 flex items-center justify-center text-text">
                🖼️
              </div>
              <div className="text-sm font-semibold text-text">Görsel yüklenemedi</div>
              <div className="text-xs text-text-muted">Daha sonra tekrar deneyin.</div>
            </div>
          )}
        </div>
      </div>

      {/* Thumbnails */}
      {srcs.length > 1 ? (
        <div className="mt-4">
          <div className="h-px w-full bg-white/10" />

          <div className="mt-3 flex gap-3 pb-5 pl-5 overflow-x-auto pb-1">
            {srcs.map((src, idx) => {
              const active = idx === safeIndex
              return (
                <button
                  key={`${src}-${idx}`}
                  type="button"
                  onClick={() => {
                    setImgError(false)
                    setActiveIndex(idx)
                  }}
                  className={[
                    "shrink-0 rounded-2xl overflow-hidden border transition",
                    active ? "border-primary" : "border-white/10 hover:border-white/20",
                  ].join(" ")}
                  aria-label={`Görsel ${idx + 1}`}
                >
                  <div className="w-24 h-16 bg-surface">
                    <img
                      src={src}
                      alt={`thumb ${idx + 1}`}
                      className={["w-full h-full object-cover transition", expiredClass].join(" ")}
                    />
                  </div>
                </button>
              )
            })}
          </div>
        </div>
      ) : null}
    </div>
  )
}
