import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
import styled from 'styled-components';
import { useLocale } from '@/app/providers/LocaleProvider';

const Overlay = styled.div`
  position: fixed;
  inset: 0;
  background-color: ${({ theme }) => theme.colors.overlay};
  display: flex;
  align-items: center;
  justify-content: center;
  padding: ${({ theme }) => theme.spacing[6]};
  z-index: ${({ theme }) => theme.zIndex.modal + 10};
`;

const Image = styled.img`
  max-width: min(92vw, 960px);
  max-height: 88vh;
  border-radius: ${({ theme }) => theme.borderRadius.lg};
  box-shadow: ${({ theme }) => theme.shadows.xl};
  object-fit: contain;
`;

const CloseButton = styled.button`
  position: fixed;
  top: ${({ theme }) => theme.spacing[6]};
  inset-inline-end: ${({ theme }) => theme.spacing[6]};
  width: 44px;
  height: 44px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  border: none;
  background-color: ${({ theme }) => theme.colors.surface};
  color: ${({ theme }) => theme.colors.text.primary};
  font-size: 1.25rem;
  cursor: pointer;
  box-shadow: ${({ theme }) => theme.shadows.md};

  &:focus-visible {
    outline: 2px solid ${({ theme }) => theme.colors.primary};
    outline-offset: 2px;
  }
`;

interface ImageLightboxProps {
  src: string;
  alt: string;
  onClose: () => void;
}

export const ImageLightbox: React.FC<ImageLightboxProps> = ({ src, alt, onClose }) => {
  const { t } = useLocale();

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

  return createPortal(
    <Overlay onClick={onClose} role="dialog" aria-modal="true" aria-label={alt}>
      <CloseButton type="button" onClick={onClose} aria-label={t('common:actions.close')}>
        ✕
      </CloseButton>
      <Image src={src} alt={alt} onClick={(e) => e.stopPropagation()} />
    </Overlay>,
    document.body,
  );
};
