'use client';

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { cn } from '@/lib/utils/cn';

/*
 * Settings page building blocks, ported from includes/settings-ui.php and the
 * behaviour in assets/js/settings.js + settings-pages.js. Styles: settings.css,
 * settings-pages.css (bundled via src/styles/crm-app.css).
 */

/* ------------------------------------------------------------ validation */

type FieldInput = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;

function fieldError(input: FieldInput) {
  const v = input.validity;
  if (v.valueMissing) return 'required';
  if (
    v.typeMismatch ||
    v.patternMismatch ||
    v.tooShort ||
    v.rangeUnderflow ||
    v.rangeOverflow ||
    v.badInput
  ) {
    return 'invalid';
  }
  return '';
}

/**
 * Port of `CRM.validate(form)`: checks `.input[required]` and email inputs, marks
 * their `.field` with `.is-invalid`, focuses the first bad one.
 */
export function validateForm(form: HTMLFormElement): boolean {
  let first: FieldInput | null = null;
  form
    .querySelectorAll<FieldInput>(
      '.input[required], .input[type="email"], .input[type="number"], .input[pattern], .input[minlength]',
    )
    .forEach((input) => {
      if (input.disabled) return;
      const bad = !!fieldError(input);
      input.closest('.field')?.classList.toggle('is-invalid', bad);
      input.setAttribute('aria-invalid', bad ? 'true' : 'false');
      if (bad && !first) first = input;
    });
  (first as FieldInput | null)?.focus();
  return !first;
}

/** Clears `.is-invalid` once the field is valid again (use as a form's onInput). */
export function clearFixedFields(e: React.FormEvent<HTMLFormElement>) {
  const input = e.target as FieldInput;
  const field = input.closest?.('.field.is-invalid');
  if (field && !fieldError(input)) field.classList.remove('is-invalid');
}

/* -------------------------------------------------------------- save bar */

/** Saves a settings form; resolve `false` to keep the unsaved changes (e.g. after an error). */
export type SettingsSaveHandler = (form: HTMLFormElement) => Promise<void | false> | void | false;

interface SaveBarApi {
  markDirty: (form: HTMLFormElement) => void;
  register: (form: HTMLFormElement, onSave: SettingsSaveHandler | undefined) => () => void;
  save: () => void;
}

const SaveBarContext = createContext<SaveBarApi | null>(null);

/** Access the settings save-bar API (markDirty / save) from inside a SettingsFormsProvider. */
export function useSettingsSaveBar() {
  return useContext(SaveBarContext);
}

/** Makes the form's current values its defaults, so a later Cancel resets to them. */
function commitDefaults(form: HTMLFormElement) {
  form.querySelectorAll<FieldInput>('input, select, textarea').forEach((el) => {
    if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) {
      el.defaultChecked = el.checked;
    } else if (el instanceof HTMLSelectElement) {
      Array.from(el.options).forEach((o) => (o.defaultSelected = o.selected));
    } else if (!(el instanceof HTMLInputElement && el.type === 'file')) {
      el.defaultValue = el.value;
    }
  });
}

/**
 * Tracks the settings forms with unsaved changes (one per tab, possibly several) and
 * shows the bottom save bar (`su_save_bar()`). Save validates them all, runs each
 * form's `onSave` (the API call) in turn and makes the saved values the new defaults;
 * a form whose save fails stays unsaved. Cancel resets them all.
 * Wrap a settings page in this provider.
 */
export function SettingsFormsProvider({ children }: { children: React.ReactNode }) {
  const toast = useToast();
  const dirty = useRef(new Set<HTMLFormElement>());
  const handlers = useRef(new Map<HTMLFormElement, SettingsSaveHandler | undefined>());
  const [visible, setVisible] = useState(false);
  const [saving, setSaving] = useState(false);

  const markDirty = useCallback((form: HTMLFormElement) => {
    dirty.current.add(form);
    setVisible(true);
  }, []);

  // #500: leaving the page with the save bar up used to drop the edits with no warning.
  useEffect(() => {
    if (!visible) return;
    const onLeave = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = '';
    };
    const onClick = (event: MouseEvent) => {
      const link = (event.target as Element | null)?.closest?.('a');
      if (!link || link.target === '_blank') return;
      if (link.origin !== window.location.origin) return;
      if (window.confirm('You have unsaved changes. Leave this page?')) return;
      event.preventDefault();
      event.stopPropagation();
    };
    window.addEventListener('beforeunload', onLeave);
    document.addEventListener('click', onClick, true);
    return () => {
      window.removeEventListener('beforeunload', onLeave);
      document.removeEventListener('click', onClick, true);
    };
  }, [visible]);

  const register = useCallback((form: HTMLFormElement, onSave: SettingsSaveHandler | undefined) => {
    handlers.current.set(form, onSave);
    return () => {
      handlers.current.delete(form);
      dirty.current.delete(form);
    };
  }, []);

  const save = useCallback(async () => {
    const forms = [...dirty.current];
    if (!forms.length || saving) return;
    const invalid = forms.filter((f) => !validateForm(f));
    if (invalid.length) {
      toast(
        invalid.some((f) => f.closest('[role="tabpanel"]')?.classList.contains('crm-d-none'))
          ? 'Please fix the highlighted fields (also on other tabs)'
          : 'Please fix the highlighted fields',
        'danger',
      );
      return;
    }
    setSaving(true);
    try {
      for (const form of forms) {
        const onSave = handlers.current.get(form);
        if (onSave && (await onSave(form)) === false) continue; // stays unsaved
        commitDefaults(form);
        dirty.current.delete(form);
      }
      if (dirty.current.size === 0) {
        setVisible(false);
        toast('Changes saved', 'success');
      }
    } finally {
      setSaving(false);
    }
  }, [saving, toast]);

  const cancel = () => {
    for (const form of dirty.current) {
      form.reset();
      form.querySelectorAll('.field.is-invalid').forEach((f) => f.classList.remove('is-invalid'));
    }
    dirty.current.clear();
    setVisible(false);
  };

  useEffect(() => {
    if (!visible) return;
    const onUnload = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, [visible]);

  const api = useMemo(() => ({ markDirty, register, save }), [markDirty, register, save]);

  return (
    <SaveBarContext.Provider value={api}>
      {children}
      <div
        className={cn('save-bar', visible && 'is-visible')}
        role="region"
        aria-label="Unsaved changes"
      >
        <span className="save-bar__text">You have unsaved changes</span>
        <button type="button" className="btn-crm btn-crm--outline" onClick={cancel}>
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', saving && 'is-loading')}
          aria-busy={saving}
          disabled={saving}
          onClick={save}
        >
          <span className="btn-crm__spinner" aria-hidden />
          Save
        </button>
      </div>
    </SaveBarContext.Provider>
  );
}

/**
 * `form[data-settings-form]`: any change shows the save bar. Inputs inside stay
 * uncontrolled (defaultValue / defaultChecked) so Cancel can `form.reset()`.
 * `onSave` does the API call (no handler: the save is local only). `onReset` runs
 * after a reset, for previews that mirror field values. `readOnly` disables every
 * field (e.g. account settings for non-admins).
 */
export function SettingsForm({
  id,
  className,
  onSave,
  onReset,
  readOnly = false,
  children,
}: {
  id?: string;
  className?: string;
  onSave?: SettingsSaveHandler;
  onReset?: (form: HTMLFormElement) => void;
  readOnly?: boolean;
  children: React.ReactNode;
}) {
  const api = useContext(SaveBarContext);
  const ref = useRef<HTMLFormElement>(null);
  const onSaveRef = useRef(onSave);
  onSaveRef.current = onSave;
  const register = api?.register;
  // Keep a stable handler so onSave identity changes do not unregister the form
  // (which would clear dirty mid-edit for controlled settings like Sales Workspace).
  useEffect(() => {
    if (!ref.current || !register) return;
    const stableSave: SettingsSaveHandler = (form) => onSaveRef.current?.(form);
    return register(ref.current, stableSave);
  }, [register]);
  // read-only: disable the controls (a wrapping <fieldset> would break `.set-stack > *` rules)
  useEffect(() => {
    if (!readOnly) return;
    ref.current
      ?.querySelectorAll<FieldInput>('input, select, textarea')
      .forEach((el) => (el.disabled = true));
  }, [readOnly]);
  const mark = (e: React.FormEvent<HTMLFormElement>) => {
    clearFixedFields(e);
    if (!readOnly) api?.markDirty(e.currentTarget);
  };
  return (
    <form
      id={id}
      ref={ref}
      className={className}
      data-settings-form
      noValidate
      onInput={mark}
      onChange={mark}
      onSubmit={(e) => {
        e.preventDefault();
        api?.save();
      }}
      onReset={(e) => {
        const form = e.currentTarget;
        // the reset event fires before the values change
        if (onReset) window.setTimeout(() => onReset(form));
      }}
    >
      {children}
    </form>
  );
}

/* ------------------------------------------------------------------ tabs */

export interface TabDef {
  id: string;
  label: string;
}

/**
 * Active tab that follows `#hash` (settings.js): opening `/settings/x#tab-email`
 * selects that tab, clicking a tab updates the hash without scrolling. With no hash, `initial`
 * (default: the first tab) is open.
 */
export function useHashTab(tabs: TabDef[], initial?: string) {
  const [active, setActive] = useState(initial ?? tabs[0]?.id ?? '');
  useEffect(() => {
    const id = window.location.hash.slice(1);
    if (id && tabs.some((t) => t.id === id)) {
      setActive(id);
      window.requestAnimationFrame(() => window.scrollTo(0, 0));
    }
    // tabs are static per page
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const select = (id: string) => {
    setActive(id);
    window.history.replaceState(null, '', `#${id}`);
  };
  return [active, select] as const;
}

/** `.set-tabs` bar (boxed = `su_tabs()`). */
export function SetTabs({
  label,
  tabs,
  active,
  onSelect,
  boxed = false,
  className,
}: {
  label: string;
  tabs: TabDef[];
  active: string;
  onSelect: (id: string) => void;
  boxed?: boolean;
  className?: string;
}) {
  return (
    <nav
      className={cn('set-tabs', boxed && 'set-tabs--boxed', className)}
      role="tablist"
      aria-label={label}
    >
      {tabs.map((t) => (
        <button
          key={t.id}
          type="button"
          className={cn('set-tab', active === t.id && 'active')}
          role="tab"
          aria-selected={active === t.id}
          aria-controls={t.id}
          onClick={() => onSelect(t.id)}
        >
          {t.label}
        </button>
      ))}
    </nav>
  );
}

/** Tab panel: stays mounted (so unsaved form values survive tab switches). */
export function TabPanel({
  id,
  active,
  children,
}: {
  id: string;
  active: string;
  children: React.ReactNode;
}) {
  return (
    <section id={id} className={cn(active !== id && 'crm-d-none')} role="tabpanel">
      {children}
    </section>
  );
}

/* --------------------------------------------------------------- dialogs */

/**
 * Modals of the Settings pages (settings.css `dialog.set-modal`, as in
 * includes/settings-ui.php). Sales pages use FormDrawer / CrmModal (modal.css) instead.
 *
 * Native `<dialog class="set-modal">`, opened with showModal(). `drawer` slides in
 * from the right (`set-modal--drawer`); otherwise it is a centred confirmation.
 * Esc and a click on the backdrop close it.
 */
export function SetDialog({
  open,
  onClose,
  drawer = false,
  labelledBy,
  id,
  className,
  style,
  children,
}: {
  open: boolean;
  onClose: () => void;
  drawer?: boolean;
  labelledBy: string;
  id?: string;
  className?: string;
  style?: React.CSSProperties;
  children: React.ReactNode;
}) {
  const ref = useRef<HTMLDialogElement>(null);
  useEffect(() => {
    const d = ref.current;
    if (!d) return;
    // Side panels (set-modal--drawer / set-calling-modal) use CSS inset; do not centre them.
    const sidePanel =
      drawer ||
      d.classList.contains('set-modal--drawer') ||
      d.classList.contains('set-calling-modal');
    const clearSidePanelInline = () => {
      d.style.top = '';
      d.style.left = '';
      d.style.right = '';
      d.style.bottom = '';
      d.style.margin = '';
      d.style.transform = '';
    };
    const center = () => {
      // Top-layer <dialog> resolves %/vh/vw inset against a zero box; use pixels.
      if (sidePanel || !d.open) return;
      const w = d.offsetWidth;
      const h = d.offsetHeight;
      d.style.top = `${Math.max(16, (window.innerHeight - h) / 2)}px`;
      d.style.left = `${Math.max(16, (window.innerWidth - w) / 2)}px`;
      d.style.right = 'auto';
      d.style.bottom = 'auto';
      d.style.margin = '0';
      d.style.transform = 'none';
    };
    if (open && !d.open) {
      d.showModal();
      if (sidePanel) clearSidePanelInline();
      else requestAnimationFrame(center);
      d.querySelector<HTMLElement>('input:not([type=radio]), select')?.focus();
    } else if (!open && d.open) {
      d.close();
    }
    if (sidePanel || !open) return;
    const ro = new ResizeObserver(() => requestAnimationFrame(center));
    ro.observe(d);
    window.addEventListener('resize', center);
    return () => {
      ro.disconnect();
      window.removeEventListener('resize', center);
    };
  }, [open, drawer]);
  return (
    <dialog
      ref={ref}
      id={id}
      className={cn('set-modal', drawer && 'set-modal--drawer', className)}
      aria-labelledby={labelledBy}
      style={style}
      onClose={onClose}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      {children}
    </dialog>
  );
}

/** `su_dialog_head()`: title + close button. */
export function DialogHead({
  id,
  title,
  onClose,
}: {
  id: string;
  title: React.ReactNode;
  onClose: () => void;
}) {
  return (
    <div className="set-modal__head">
      <h2 className="set-modal__title" id={id}>
        {title}
      </h2>
      <button
        type="button"
        className="icon-btn icon-btn--ghost"
        aria-label="Close"
        onClick={onClose}
      >
        <CrmIcon name="x" className="iconSize-20" />
      </button>
    </div>
  );
}

/**
 * `su_drawer()`: right-side dialog with a form. Submit validates, calls `onSave`
 * with the form data, toasts the success text (onSave may return a different
 * one, or `false` to keep the dialog open), resets unless `keep`, and closes.
 */
export function DrawerForm({
  id,
  title,
  open,
  onClose,
  submitLabel = 'Save',
  success = 'Saved',
  keep = false,
  drawer = true,
  onSave,
  footer,
  children,
}: {
  id: string;
  title: React.ReactNode;
  open: boolean;
  onClose: () => void;
  submitLabel?: string;
  success?: string;
  keep?: boolean;
  drawer?: boolean;
  onSave?: (
    data: FormData,
    form: HTMLFormElement,
  ) => string | false | void | Promise<string | false | void>;
  footer?: React.ReactNode;
  children: React.ReactNode;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState(false);
  return (
    <SetDialog
      id={id}
      open={open}
      onClose={onClose}
      drawer={drawer}
      labelledBy={`${id}-title`}
    >
      <form
        noValidate
        onInput={clearFixedFields}
        onSubmit={async (e) => {
          e.preventDefault();
          const form = e.currentTarget;
          if (busy || !validateForm(form)) return;
          setBusy(true);
          let result: string | false | void;
          try {
            result = await onSave?.(new FormData(form), form);
          } catch {
            result = false;
          } finally {
            setBusy(false);
          }
          if (result === false) return;
          toast(typeof result === 'string' ? result : success, 'success');
          if (!keep) form.reset();
          onClose();
        }}
      >
        <DialogHead id={`${id}-title`} title={title} onClose={onClose} />
        <div className="set-modal__body">{children}</div>
        <div className="set-modal__foot">
          {footer}
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          {submitLabel ? (
            <button
              type="submit"
              className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
              aria-busy={busy}
              disabled={busy}
            >
              {submitLabel}
            </button>
          ) : null}
        </div>
      </form>
    </SetDialog>
  );
}

/* -------------------------------------------------------------- controls */

/** `su_toggle()`: switch on the left, title + description on the right. */
export function SuToggle({
  name,
  title,
  desc,
  extra,
  defaultChecked = false,
}: {
  name: string;
  title: string;
  desc?: string;
  /** Inline control after the title (e.g. “Allow desktop pop-ups”). */
  extra?: React.ReactNode;
  defaultChecked?: boolean;
}) {
  const id = `tg-${name.replace(/[^a-z0-9_-]/gi, '-')}`;
  return (
    <div className="su-toggle">
      <label className="switch">
        <input type="checkbox" id={id} name={name} defaultChecked={defaultChecked} />
        <span className="switch__track" />
      </label>
      <div className="su-toggle__body">
        <label className="su-toggle__title" htmlFor={id}>
          {title}
        </label>
        {extra}
        {desc ? <p className="su-toggle__desc">{desc}</p> : null}
      </div>
    </div>
  );
}

/** `.set-row` with a title, description and a switch on the right. */
export function SetSwitchRow({
  name,
  title,
  desc,
  defaultChecked = false,
  disabled = false,
  srLabel,
}: {
  name: string;
  title: string;
  desc: string;
  defaultChecked?: boolean;
  disabled?: boolean;
  srLabel: string;
}) {
  return (
    <div className="set-row">
      <div>
        <p className="set-row__title">{title}</p>
        <p className="set-row__desc">{desc}</p>
      </div>
      <label className="switch">
        <input type="checkbox" name={name} defaultChecked={defaultChecked} disabled={disabled} />
        <span className="switch__track" />
        <span className="crm-visually-hidden">{srLabel}</span>
      </label>
    </div>
  );
}

/** `su_check()`: checkbox + label. */
export function SuCheck({
  name,
  label,
  value,
  defaultChecked = false,
}: {
  name: string;
  label: React.ReactNode;
  value?: string;
  defaultChecked?: boolean;
}) {
  return (
    <label className="su-check">
      <span className="check">
        <input type="checkbox" name={name} value={value} defaultChecked={defaultChecked} />
        <span className="check__box" aria-hidden />
      </span>
      <span>{label}</span>
    </label>
  );
}

/** `.su-radio` option with a bold title and a description. */
export function SuRadio({
  name,
  value,
  title,
  desc,
  defaultChecked = false,
}: {
  name: string;
  value: string;
  title: string;
  desc: string;
  defaultChecked?: boolean;
}) {
  return (
    <label className="su-radio">
      <input type="radio" name={name} value={value} defaultChecked={defaultChecked} />
      <span>
        <strong>{title}</strong>
        <span>{desc}</span>
      </span>
    </label>
  );
}

export type BadgeTone = 'success' | 'warning' | 'danger' | 'info' | 'brand' | '';

/** `su_badge()`. */
export function SuBadge({ tone = '', children }: { tone?: BadgeTone; children: React.ReactNode }) {
  return <span className={cn('badge', tone && `badge--${tone}`)}>{children}</span>;
}

/** `su_field()`: label + control (+ help) + error. Give the control `id={htmlFor}`. */
export function SuField({
  label,
  htmlFor,
  help,
  error = 'This field is required',
  full = false,
  children,
}: {
  label: React.ReactNode;
  htmlFor?: string;
  help?: React.ReactNode;
  error?: string;
  full?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div className={cn('field', full && 'field--full')}>
      <label className="field__label" htmlFor={htmlFor}>
        {label}
      </label>
      {children}
      {help ? <p className="field__help">{help}</p> : null}
      <p className="field__error">{error}</p>
    </div>
  );
}

/** Label with a hover info tip (`info_label()` in settings-account-defaults.php). */
export function InfoLabel({ htmlFor, text, tip }: { htmlFor: string; text: string; tip: string }) {
  return (
    <label className="field__label set-label" htmlFor={htmlFor}>
      {text}{' '}
      <span className="set-info" tabIndex={0} data-tip-text={tip} aria-label={tip}>
        <CrmIcon name="info" className="iconSize-16" />
      </span>
    </label>
  );
}

/** Copies text and toasts like `[data-copy]` in settings.js. */
export function useCopy() {
  const toast = useToast();
  return async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast('Copied to clipboard', 'success');
    } catch {
      toast('Could not copy. Select the text and copy it yourself.', 'danger');
    }
  };
}

/**
 * Centred "Are you sure?" dialog. Confirm runs `onConfirm` once (the button is
 * disabled while it runs) and closes when it resolves.
 */
export function ConfirmDialog({
  id,
  open,
  onClose,
  title,
  confirmLabel,
  danger = false,
  onConfirm,
  children,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  title: string;
  confirmLabel: string;
  danger?: boolean;
  onConfirm: () => Promise<void> | void;
  children: React.ReactNode;
}) {
  const [busy, setBusy] = useState(false);
  const confirm = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await onConfirm();
      onClose();
    } finally {
      setBusy(false);
    }
  };
  return (
    <SetDialog open={open} onClose={onClose} labelledBy={`${id}-title`}>
      <div>
        <DialogHead id={`${id}-title`} title={title} onClose={onClose} />
        <div className="set-modal__body">{children}</div>
        <div className="set-modal__foot">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={onClose}
            disabled={busy}
          >
            Cancel
          </button>
          <button
            type="button"
            className={cn(
              'btn-crm',
              danger ? 'btn-crm--outline su-danger' : 'btn-crm--primary',
              busy && 'is-loading',
            )}
            aria-busy={busy}
            disabled={busy}
            onClick={confirm}
          >
            {confirmLabel}
          </button>
        </div>
      </div>
    </SetDialog>
  );
}

/** Muted line for settings the API does not support yet (shown disabled, never saved). */
export function ComingSoon({
  children = 'Coming soon: this setting is not saved yet.',
}: {
  children?: React.ReactNode;
}) {
  return <p className="field__help crm-mt-2">{children}</p>;
}

/** Formats "today" like the PHP pages' {{today}} placeholder (e.g. "7 Oct 2026"). */
export const todayLabel = () =>
  new Date().toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
