import React, { useEffect, useMemo, useState } from 'react';
import {
  Box,
  Dialog,
  IconButton,
  Typography,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import styled from 'styled-components/macro';

export type PreviewImage = {
  id: number;
  src: string;
  alt?: string;
};

interface ImagePreviewDialogProps {
  open: boolean;
  images: PreviewImage[];
  initialIndex?: number;
  onClose: () => void;
}

const NavButton = styled(IconButton)`
  position: absolute !important;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  background: rgba(0, 0, 0, 0.45) !important;
  color: #fff !important;

  &:hover {
    background: rgba(0, 0, 0, 0.65) !important;
  }

  &:disabled {
    color: rgba(255, 255, 255, 0.3) !important;
  }
`;

const Stage = styled(Box)`
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
`;

const OverlayCounter = styled(Typography)`
  position: absolute;
  top: 16px;
  left: 24px;
  z-index: 20;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7);
`;

const CloseButton = styled(IconButton)`
  position: absolute !important;
  top: 10px;
  right: 16px;
  z-index: 20;
  color: #fff !important;
  background: rgba(0, 0, 0, 0.3) !important;

  &:hover {
    background: rgba(0, 0, 0, 0.5) !important;
  }
`;

const LeftNavButton = styled(NavButton)`
  left: 16px;
`;

const RightNavButton = styled(NavButton)`
  right: 16px;
`;

const ImageFrame = styled(Box)`
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const PreviewImageView = styled.img`
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
`;

export default function ImagePreviewDialog({
  open,
  images,
  initialIndex = 0,
  onClose,
}: ImagePreviewDialogProps) {
  const [index, setIndex] = useState(initialIndex);
  const hasMultipleImages = images.length > 1;

  useEffect(() => {
    if (!open) {
      return;
    }

    if (images.length === 0) {
      setIndex(0);
      return;
    }

    const safeStartIndex = Math.min(Math.max(initialIndex, 0), images.length - 1);
    setIndex(safeStartIndex);
  }, [open, images.length, initialIndex]);

  const canGoBack = index > 0;
  const canGoForward = index < images.length - 1;

  const activeImage = useMemo(() => {
    if (images.length === 0) {
      return null;
    }

    return images[index] ?? images[0];
  }, [images, index]);

  const goBack = () => setIndex((prev) => Math.max(prev - 1, 0));
  const goForward = () => setIndex((prev) => Math.min(prev + 1, images.length - 1));

  useEffect(() => {
    if (!open) {
      return;
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        onClose();
      } else if (event.key === 'ArrowLeft' && hasMultipleImages) {
        event.preventDefault();
        setIndex((prev) => Math.max(prev - 1, 0));
      } else if (event.key === 'ArrowRight' && hasMultipleImages) {
        event.preventDefault();
        setIndex((prev) => Math.min(prev + 1, images.length - 1));
      }
    };

    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [open, hasMultipleImages, images.length, onClose]);

  return (
    <Dialog open={open} onClose={onClose} fullScreen>
      <Stage>
        <OverlayCounter variant='h6'>
          {images.length > 0 ? `${index + 1} / ${images.length}` : '0 / 0'}
        </OverlayCounter>

        <CloseButton onClick={onClose} size='large'>
          <CloseIcon />
        </CloseButton>

        {hasMultipleImages && (
          <LeftNavButton onClick={goBack} disabled={!canGoBack} size='large'>
            <ArrowBackIosNewIcon />
          </LeftNavButton>
        )}

        {activeImage != null && (
          <ImageFrame>
            <PreviewImageView src={activeImage.src} alt={activeImage.alt ?? 'Preview'} />
          </ImageFrame>
        )}

        {hasMultipleImages && (
          <RightNavButton onClick={goForward} disabled={!canGoForward} size='large'>
            <ArrowForwardIosIcon />
          </RightNavButton>
        )}
      </Stage>
    </Dialog>
  );
}
