'use client';

import type { ReactNode } from 'react';
import { useEffect } from 'react';
import { copy } from '@/shared/i18n';
import { cn } from '@/shared/lib/cn';
import { useReducedMotion } from '@/shared/lib/useReducedMotion';

interface ModalProps {
  isOpen: boolean;
  title: string;
  description?: string;
  onClose: () => void;
  children: ReactNode;
  footer?: ReactNode;
}

export const Modal = ({
  isOpen,
  title,
  description,
  onClose,
  children,
  footer,
}: ModalProps) => {
  const reducedMotion = useReducedMotion();

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

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', onKeyDown);

    return () => {
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [isOpen, onClose]);

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center p-4 sm:items-center">
      <button
        type="button"
        aria-label={copy.modal.closeAriaLabel}
        onClick={onClose}
        className="absolute inset-0 bg-slate-900/52 backdrop-blur-[2px]"
      />

      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="custom-entry-modal-title"
        className={cn(
          'relative z-10 w-full max-w-3xl overflow-hidden rounded-3xl border border-white/35 bg-[linear-gradient(160deg,rgba(248,250,252,0.9)_0%,rgba(226,232,240,0.84)_52%,rgba(203,213,225,0.86)_100%)] shadow-[0_24px_90px_rgba(15,23,42,0.32)]',
          reducedMotion
            ? 'transition-none'
            : 'transition-transform duration-300 ease-out motion-reduce:transition-none',
        )}
      >
        <header className="border-b border-brand-dark/14 px-6 py-5 sm:px-7">
          <div className="flex items-start justify-between gap-4">
            <div>
              <h2 id="custom-entry-modal-title" className="text-lg font-semibold text-brand-dark">
                {title}
              </h2>
              {description ? (
                <p className="mt-1 text-sm text-brand-dark/64">{description}</p>
              ) : null}
            </div>
            <button
              type="button"
              onClick={onClose}
              className="rounded-lg border border-brand-dark/16 bg-white/58 px-2.5 py-1.5 text-xs text-brand-dark/82 transition hover:bg-white/84 hover:text-brand-dark"
            >
              {copy.modal.closeButton}
            </button>
          </div>
        </header>

        <div className="max-h-[72vh] overflow-y-auto px-6 py-5 sm:px-7">{children}</div>

        {footer ? (
          <footer className="border-t border-brand-dark/12 bg-white/56 px-6 py-4 sm:px-7">{footer}</footer>
        ) : null}
      </div>
    </div>
  );
};
