'use client';

import { useState } from 'react';

import Image from 'next/image';

import Lightbox from 'yet-another-react-lightbox';
import Zoom from 'yet-another-react-lightbox/plugins/zoom';
import 'yet-another-react-lightbox/styles.css';

import { cn } from '@/lib/utils';
import { buildMediaUrl } from '@/utils/images';

import { ImageObject } from '@/types/Common';

interface EventImageDialogProps {
  imageUrl: string;
  eventName: string;
  locale: string;
  imageWidth?: number;
  imageHeight?: number;
  galleryImages?: ImageObject[] | null;
  className?: string;
}

const EventImageDialog = ({
  imageUrl,
  eventName,
  locale,
  imageWidth,
  imageHeight,
  galleryImages,
  className,
}: EventImageDialogProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const isHu = locale.startsWith('hu');
  const openAriaLabel = isHu ? 'Kép megnyitása' : 'Open image';

  const previewUrl =
    imageUrl || (galleryImages?.[0]?.id ? buildMediaUrl(galleryImages[0].id, 'w1920') : null);
  const previewWidth = imageWidth ?? galleryImages?.[0]?.width;
  const previewHeight = imageHeight ?? galleryImages?.[0]?.height;

  if (!previewUrl) return null;

  const slides =
    galleryImages && galleryImages.length > 0
      ? galleryImages.map((image) => ({
          src: buildMediaUrl(image.id, 'w1920'),
          width: image.width,
          height: image.height,
          title: image.kepalairas || eventName,
        }))
      : [
          {
            src: previewUrl,
            width: previewWidth,
            height: previewHeight,
            title: eventName,
          },
        ];

  return (
    <>
      <button
        type="button"
        aria-label={openAriaLabel}
        onClick={() => setIsOpen(true)}
        className={cn(
          className,
          'relative min-h-[320px] w-full cursor-zoom-in overflow-hidden bg-mma-cyan/20 text-left shadow-[0_36px_84px_-64px_rgba(20,25,40,0.3)] sm:min-h-[400px] lg:min-h-[520px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mma-blue focus-visible:ring-offset-2'
        )}
      >
        <Image
          src={previewUrl}
          alt={eventName}
          fill
          className="object-contain"
          sizes="(min-width: 1024px) 44vw, 100vw"
          priority
        />
      </button>

      <Lightbox
        open={isOpen}
        close={() => setIsOpen(false)}
        plugins={[Zoom]}
        zoom={{ maxZoomPixelRatio: 3, scrollToZoom: true }}
        carousel={{ padding: 60, finite: true, preload: 1 }}
        render={{
          buttonPrev: () => null,
          buttonNext: () => null,
        }}
        slides={slides}
      />
    </>
  );
};

export default EventImageDialog;
