'use client';

import { ReactNode, useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogOverlay,
  DialogTitle
} from '../ui/dialog';
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  type CarouselApi
} from '../ui/carousel';
import Image from 'next/image';
import { Button } from '../ui/button';
import { X } from 'lucide-react';
import { PostMediaData } from '@/lib/database';
import { ImageQuality } from '@/config/enums/image-quality';
import { cn } from '@/lib/utils';

export default function ImagePreview({
  children,
  currentImgId,
  media
}: {
  children: ReactNode;
  currentImgId?: string;
  media: PostMediaData[] | undefined | null;
}) {
  const [open, setOpen] = useState(false);
  const [curIndex, setCurIndex] = useState(0);
  const [api, setApi] = useState<CarouselApi | null>(null);

  const onImageClick = () => {
    setOpen(true);
    if (media?.length) {
      const index = media.findIndex((item) => item.id === currentImgId);
      setCurIndex(index !== -1 ? index : 0);
    }
  };

  useEffect(() => {
    if (open && api) {
      api.scrollTo(curIndex, true);
    }
  }, [open, api, curIndex]);

  return (
    <>
      <div onClick={onImageClick} className='cursor-pointer'>
        {children}
      </div>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogOverlay className='bg-black/80' />
        <DialogContent
          showCloseButton={false}
          className='flex w-full max-w-none min-w-[80vw] flex-col items-center justify-center border-0 bg-transparent p-0 shadow-none lg:min-w-4xl xl:min-w-5xl'
        >
          <Button
            variant='ghost'
            size='icon'
            onClick={() => setOpen(false)}
            className='fixed top-4 right-4 z-20 rounded-full bg-white hover:bg-neutral-200 sm:-right-12'
          >
            <X className='size-5 text-black' />
          </Button>

          <Carousel
            setApi={setApi}
            className='relative w-full'
            opts={{
              loop: true
            }}
          >
            <CarouselContent>
              {media?.map((item, index) => (
                <CarouselItem
                  key={index}
                  className='flex items-center justify-center'
                >
                  <div className='flex h-screen w-screen flex-col items-center justify-center gap-2'>
                    <div className='relative size-full max-h-[80vw] flex-1'>
                      <Image
                        src={item.url}
                        alt={item?.alt || 'Article image'}
                        fill
                        className='object-contain'
                        quality={ImageQuality.HIGH}
                      />
                    </div>
                    <div className='my-4 text-center text-white'>
                      <DialogTitle
                        className={cn(
                          'text-lg font-semibold',
                          !item?.caption && 'sr-only'
                        )}
                      >
                        {item?.caption || 'No caption available'}
                      </DialogTitle>
                      <DialogDescription
                        className={cn(
                          'text-sm text-gray-300',
                          !item?.author && 'sr-only'
                        )}
                      >
                        {item?.author || 'Unknown author'}
                      </DialogDescription>
                    </div>
                  </div>
                </CarouselItem>
              ))}
            </CarouselContent>
            {!!media && media.length > 1 && (
              <>
                <CarouselPrevious className='left-4 sm:-left-12' />
                <CarouselNext className='right-4 sm:-right-12' />
              </>
            )}
          </Carousel>
        </DialogContent>
      </Dialog>
    </>
  );
}
