'use client';

import { useEffect, useState } from 'react';
import type { MessageAttachment } from '@alqove/api-client';

interface Props {
  open: boolean;
  onClose: () => void;
  attachments: MessageAttachment[];
  startIndex?: number;
}

function LightboxBody({
  onClose,
  attachments,
  startIndex,
}: {
  onClose: () => void;
  attachments: MessageAttachment[];
  startIndex: number;
}) {
  const [index, setIndex] = useState(startIndex);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight')
        setIndex((i) => Math.min(i + 1, attachments.length - 1));
      if (e.key === 'ArrowLeft') setIndex((i) => Math.max(i - 1, 0));
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [attachments.length, onClose]);

  const current = attachments[index];
  if (!current) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 p-4"
      onClick={onClose}
    >
      <button
        type="button"
        onClick={(e) => {
          e.stopPropagation();
          onClose();
        }}
        aria-label="Close"
        className="absolute right-4 top-4 rounded-full bg-white/10 px-3 py-1 text-white hover:bg-white/20"
      >
        ✕
      </button>
      <img
        src={current.url}
        alt={`Attachment ${index + 1} of ${attachments.length}`}
        className="max-h-[90vh] max-w-full object-contain"
        onClick={(e) => e.stopPropagation()}
      />
    </div>
  );
}

export function MessageLightbox({
  open,
  onClose,
  attachments,
  startIndex = 0,
}: Props) {
  if (!open) return null;
  return (
    <LightboxBody
      onClose={onClose}
      attachments={attachments}
      startIndex={startIndex}
    />
  );
}
