'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useFocusTrap } from '@/lib/hooks/useFocusTrap';
import { cn } from '@/lib/utils/cn';

/** The open modals, oldest first: Escape reaches only the last. */
const openDrawers: object[] = [];

/**
 * Modals of the Sales pages (Inbox, Meetings, …): `.modal-backdrop` + `.modal` from
 * modal.css, as in includes/sales-ui.php. Settings pages use their own native
 * `<dialog class="set-modal">` (SetDialog / DrawerForm in features/settings), because
 * the design styles them with settings.css; use the one that matches the page's CSS.
 *
 * `.modal-backdrop` + `.modal` (modal.css). Drawer variant slides in from the right,
 * the plain variant is centred. Esc and a click on the backdrop close it; the page
 * behind does not scroll while it is open. Ported from sales-common.js.
 */
export function CrmModal({
  id,
  open,
  onClose,
  drawer = false,
  size,
  className,
  plainBackdrop = false,
  children,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  drawer?: boolean;
  size?: 'wide' | 'lg';
  /** PH1: an extra class on `.modal` (the property history's wide drawer). */
  className?: string;
  /** No dim or blur behind the drawer (HubSpot's sequence drawers); off for every other modal. */
  plainBackdrop?: boolean;
  children: React.ReactNode;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const dialogRef = useRef<HTMLDivElement>(null);
  // QA round 1 BUG-06: Tab stays inside the open dialog (as the Create segment dialog, QA #642).
  useFocusTrap(dialogRef, open);

  useEffect(() => {
    if (!open) return;
    document.body.style.overflow = 'hidden';
    const focusTimer = window.setTimeout(() => {
      ref.current
        ?.querySelector<HTMLElement>(
          'input:not([type=hidden]):not([type=checkbox]), select, textarea',
        )
        ?.focus();
    }, 60);
    openDrawers.push(ref);
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      // QA go-live (Tickets 974): with drawers stacked, Escape closes the topmost one only.
      if (openDrawers[openDrawers.length - 1] !== ref) return;
      // QA round 2 Tickets BUG-02: a "Discard unsaved changes?" confirm that onClose opens is a
      // native dialog; without this the same Esc press cancels it at once and nothing happens.
      e.preventDefault();
      onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => {
      window.clearTimeout(focusTimer);
      window.removeEventListener('keydown', onKey);
      openDrawers.splice(openDrawers.indexOf(ref), 1);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  return (
    <div
      ref={ref}
      className={cn(
        'modal-backdrop',
        drawer && 'modal-backdrop--drawer',
        plainBackdrop && 'modal-backdrop--plain',
        open && 'is-open',
      )}
      id={id}
      aria-hidden={!open}
      // HUB-620: a closed modal stays in the page (for its open animation); inert keeps its
      // buttons out of focus, clicks and the accessibility tree, so "Delete" or "Save" of a
      // hidden dialog is never the one found or tabbed to.
      inert={!open}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        ref={dialogRef}
        className={cn('modal', size && `modal--${size}`, className)}
        // CT-003: only the open modal is a dialog, so closed ones are not found as empty dialogs.
        role={open ? 'dialog' : undefined}
        aria-modal={open || undefined}
        aria-labelledby={open ? `${id}-title` : undefined}
      >
        {children}
      </div>
    </div>
  );
}

/** `.modal__header` with the title (id `${id}-title`) and a close button. */
export function ModalHeader({
  id,
  title,
  onClose,
}: {
  id: string;
  title: React.ReactNode;
  onClose: () => void;
}) {
  return (
    <div className="modal__header">
      <h2 className="modal__title" id={`${id}-title`}>
        {title}
      </h2>
      <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
        <CrmIcon name="x" className="iconSize-20" />
      </button>
    </div>
  );
}

/**
 * Right-side drawer with a form, ported from `modal_open()` / `modal_close()` in
 * includes/sales-ui.php and `onModalSubmit()` in sales-common.js.
 *
 * Fields marked `required` are checked on submit: an empty one gets `.is-invalid`
 * on its `.field` and focus. `validate` can add page checks first (return false to
 * stop). When all pass, `onSubmit` gets the form values; it may be async. Returning
 * (or resolving to) `false`, or throwing, keeps the drawer open with the values;
 * otherwise the form resets and the drawer closes. Styles: modal.css + sales.css.
 */
export function FormDrawer({
  id,
  title,
  size,
  submitLabel = 'Save',
  open,
  onClose,
  onSubmit,
  validate,
  submitDisabled,
  children,
}: {
  id: string;
  title: string;
  size?: 'wide' | 'lg';
  submitLabel?: string;
  open: boolean;
  onClose: () => void;
  onSubmit: (data: Record<string, string>) => void | boolean | Promise<void | boolean>;
  validate?: (form: HTMLFormElement) => boolean;
  /** Extra disable (e.g. labels still loading / failed). Busy already disables. */
  submitDisabled?: boolean;
  children: React.ReactNode;
}) {
  const [busy, setBusy] = useState(false);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = e.currentTarget;
    if (busy) return;
    if (validate && !validate(form)) return;
    let ok = true;
    form
      .querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('[required]')
      .forEach((input) => {
        const bad = !input.value.trim();
        input.closest('.field')?.classList.toggle('is-invalid', bad);
        if (bad && ok) {
          input.focus();
          ok = false;
        }
      });
    if (!ok) return;
    const data: Record<string, string> = {};
    new FormData(form).forEach((value, key) => {
      data[key] = String(value);
    });
    setBusy(true);
    try {
      if ((await onSubmit(data)) === false) return;
    } catch {
      return;
    } finally {
      setBusy(false);
    }
    form.reset();
    onClose();
  };

  const clearInvalid = (e: React.FormEvent<HTMLFormElement>) => {
    const target = e.target as HTMLInputElement;
    const field = target.closest('.field.is-invalid');
    if (field && target.value.trim()) field.classList.remove('is-invalid');
  };

  return (
    <CrmModal id={id} open={open} onClose={onClose} drawer size={size}>
      <form noValidate onSubmit={handleSubmit} onInput={clearInvalid}>
        <ModalHeader id={id} title={title} onClose={onClose} />
        <div className="modal__body">{children}</div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="submit"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            aria-busy={busy}
            disabled={busy || submitDisabled}
          >
            {submitLabel}
          </button>
        </div>
      </form>
    </CrmModal>
  );
}

/** Label + control + error line, ported from `field()` in includes/sales-ui.php. */
export function Field({
  label,
  htmlFor,
  className,
  error = 'This field is required.',
  errorId,
  title,
  children,
}: {
  label: string;
  htmlFor?: string;
  className?: string;
  error?: string;
  /**
   * The error line's id, for the input's `aria-describedby`; it also makes the line an alert, as
   * the design's record editor (record-page.js:226). Only Edit contact passes it (CQ1 #13).
   */
  errorId?: string;
  title?: string;
  children: React.ReactNode;
}) {
  return (
    <div className={cn('field', className)}>
      <label className="field__label" htmlFor={htmlFor} title={title}>
        {label}
      </label>
      {children}
      <span className="field__error" id={errorId} role={errorId ? 'alert' : undefined}>
        {error}
      </span>
    </div>
  );
}
