'use client';

import { useEffect, useRef, useState } from 'react';
import { errorText } from '@/lib/api/errors';
import { useFocusTrap } from '@/lib/hooks/useFocusTrap';
import { previewBookingEmail } from '../../api.client';
import type { BookingEmailPreview, BookingEmailPreviewBody } from '../../types';
import { GmSvg } from './gmParts';

/**
 * QA #649: the Automation step's "Preview confirmation email" / "Preview reminder email"
 * (create-meeting.css `.gm-email-preview-*`). The API renders it with the function the booking
 * email job sends with, from the page's current settings and a sample invitee, so the preview
 * and the real email can't drift. The HTML is shown in a sandboxed frame (no scripts).
 */
export function EmailPreviewDialog({
  body,
  onClose,
}: {
  /** The page's settings and which email; null: closed. */
  body: BookingEmailPreviewBody | null;
  onClose: () => void;
}) {
  const [preview, setPreview] = useState<BookingEmailPreview | null>(null);
  const [error, setError] = useState<string | null>(null);
  const dialogRef = useRef<HTMLElement>(null);
  const open = body !== null;

  // QA round 1 (BUG-07): focus goes into the dialog and Tab stays in it (it is aria-modal); on
  // close it returns to the button that opened it. Declared before the trap, so the opener is
  // read before the trap moves focus.
  useEffect(() => {
    if (!open) return;
    const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    return () => {
      if (opener?.isConnected) opener.focus();
    };
  }, [open]);
  useFocusTrap(dialogRef, open);

  useEffect(() => {
    if (!body) return;
    let alive = true;
    setPreview(null);
    setError(null);
    previewBookingEmail(body).then(
      (p) => alive && setPreview(p),
      (err) => alive && setError(errorText(err)),
    );
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => {
      alive = false;
      document.removeEventListener('keydown', onKey);
    };
  }, [body, onClose]);

  if (!body) return null;
  // create-meeting.html #gm-email-preview-backdrop: "Preview Email" for both emails.
  const heading = 'Preview Email';
  const frameTitle =
    body.kind === 'confirmation' ? 'Confirmation email preview' : 'Reminder email preview';

  return (
    <div
      className="gm-email-preview-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        ref={dialogRef}
        className="gm-email-preview-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="gm-email-preview-title"
      >
        <header>
          <h2 id="gm-email-preview-title">{heading}</h2>
          <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
            {GmSvg.close}
          </button>
        </header>
        <div className="gm-email-preview-content">
          {error ? (
            <p role="alert" className="gm-help" style={{ color: 'var(--danger)' }}>
              {error}
            </p>
          ) : !preview ? (
            <p className="gm-help">Loading preview…</p>
          ) : (
            <>
              <div className="gm-email-preview-meta">
                <span>To</span>
                <p>{preview.to}</p>
                <span>Subject</span>
                <p>{preview.subject}</p>
              </div>
              <div className="gm-email-preview-letter">
                {/* QA final BUG-16: keys pressed in the email (focus on its Reschedule link)
                    stay in the frame, so Esc never reached the listener above. allow-same-origin
                    (still no scripts) lets the dialog listen in the frame's document too. */}
                <iframe
                  title={frameTitle}
                  sandbox="allow-same-origin"
                  srcDoc={preview.html}
                  onLoad={(e) =>
                    e.currentTarget.contentDocument?.addEventListener('keydown', (k) => {
                      if (k.key === 'Escape') onClose();
                    })
                  }
                  style={{ display: 'block', width: '100%', height: 460, border: 0 }}
                />
              </div>
              <p className="gm-email-preview-signature-note">
                A sample invitee and time. The email sent has the booking&apos;s invitee, time and
                Google Meet link.
              </p>
            </>
          )}
        </div>
        <footer>
          <button type="button" className="btn-crm btn-crm--primary" onClick={onClose}>
            Close
          </button>
        </footer>
      </section>
    </div>
  );
}
