"use client";

import { useState, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { X, CaretLeft, CaretRight } from "@/lib/icons";
import { getPropertyImageUrl, getPropertyImagePreviewUrl } from "@/lib/appwrite/storage-utils";

interface ImageLightboxProps {
  imageIds: string[];
  title: string;
  initialIndex?: number;
  onClose: () => void;
}

export function ImageLightbox({ imageIds, title, initialIndex = 0, onClose }: ImageLightboxProps) {
  const [idx, setIdx] = useState(initialIndex);
  const prev = useCallback(() => setIdx((i) => (i - 1 + imageIds.length) % imageIds.length), [imageIds.length]);
  const next = useCallback(() => setIdx((i) => (i + 1) % imageIds.length), [imageIds.length]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") prev();
      if (e.key === "ArrowRight") next();
    };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose, prev, next]);

  return createPortal(
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/90"
      onClick={onClose}
    >
      {/* Kapat */}
      <button
        type="button"
        className="absolute top-4 right-4 size-9 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white transition-colors"
        onClick={onClose}
        aria-label="Kapat"
      >
        <X className="size-5" />
      </button>

      {/* Sayaç */}
      <div className="absolute top-4 left-1/2 -translate-x-1/2 text-white/70 text-sm tabular-nums select-none">
        {idx + 1} / {imageIds.length}
      </div>

      {/* Önceki */}
      {imageIds.length > 1 && (
        <button
          type="button"
          onClick={(e) => { e.stopPropagation(); prev(); }}
          className="absolute left-3 sm:left-6 size-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white transition-colors"
          aria-label="Önceki"
        >
          <CaretLeft className="size-5" />
        </button>
      )}

      {/* Ana görsel — orijinal boyut, kırpma yok */}
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={getPropertyImageUrl(imageIds[idx])}
        alt={`${title} ${idx + 1}`}
        className="max-h-[90dvh] max-w-[90vw] object-contain rounded-lg select-none"
        onClick={(e) => e.stopPropagation()}
        draggable={false}
      />

      {/* Sonraki */}
      {imageIds.length > 1 && (
        <button
          type="button"
          onClick={(e) => { e.stopPropagation(); next(); }}
          className="absolute right-3 sm:right-6 size-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white transition-colors"
          aria-label="Sonraki"
        >
          <CaretRight className="size-5" />
        </button>
      )}

      {/* Thumbnail şeridi */}
      {imageIds.length > 1 && (
        <div
          className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-1.5 overflow-x-auto max-w-[90vw] px-2 scrollbar-hide"
          onClick={(e) => e.stopPropagation()}
        >
          {imageIds.map((id, i) => (
            <button
              key={id}
              type="button"
              onClick={() => setIdx(i)}
              className={`shrink-0 w-14 h-10 rounded overflow-hidden border-2 transition-all ${
                i === idx ? "border-white" : "border-white/20 hover:border-white/50"
              }`}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={getPropertyImagePreviewUrl(id, 160, 120)}
                alt=""
                className="w-full h-full object-cover"
              />
            </button>
          ))}
        </div>
      )}
    </div>,
    document.body,
  );
}
