'use client';

// The stage move prompts of the 24 Nov design:
// - deals: "Required properties for <stage>" (list-page.js requiredModal, `.lp-modal--x`);
// - Leads, Tickets and other objects: "Complete required fields to move to <stage>"
//   (components/lead-pipeline.js prompt, `.lpl-modal`).
// A ticket closes with no prompt of its own, as in HubSpot (D-2).
// Each `ask` resolves true once its `submit` saved, false on Cancel / X / Esc / a click outside,
// which leave the record where it was.
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { cn } from '@/lib/utils/cn';
import {
  stageValuesFrom,
  toStageUi,
  type StageFieldSpec,
  type StageUiValue,
  type StageValues,
} from '../stageFields';
import { stageStyle } from '../stageRules';

const errorMessage = (err: unknown) => (err instanceof Error ? err.message : String(err));

/** Esc closes, focus goes to the first field and comes back when the dialog closes. */
function useDialogKeys(ref: React.RefObject<HTMLElement | null>, onClose: () => void) {
  const close = useRef(onClose);
  close.current = onClose;
  useEffect(() => {
    const prev = document.activeElement as HTMLElement | null;
    const timer = window.setTimeout(() => {
      ref.current?.querySelector<HTMLElement>('input, select, textarea, button')?.focus();
    }, 30);
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        close.current();
        return;
      }
      if (e.key !== 'Tab' || !ref.current) return;
      const f = Array.from(
        ref.current.querySelectorAll<HTMLElement>('button, input, select, textarea'),
      ).filter((x) => !(x as HTMLButtonElement).disabled);
      if (!f.length) return;
      if (e.shiftKey && document.activeElement === f[0]) {
        e.preventDefault();
        f[f.length - 1]!.focus();
      } else if (!e.shiftKey && document.activeElement === f[f.length - 1]) {
        e.preventDefault();
        f[0]!.focus();
      }
    };
    document.addEventListener('keydown', onKey, true);
    return () => {
      window.clearTimeout(timer);
      document.removeEventListener('keydown', onKey, true);
      if (prev?.isConnected) prev.focus();
    };
  }, [ref]);
}

function CloseIcon() {
  return (
    <svg
      viewBox="0 0 24 24"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="M18 6 6 18M6 6l12 12" />
    </svg>
  );
}

/** One input for a stage field, by its kind (lead-pipeline.js control / list-page.js lpField). */
export function StageFieldControl({
  spec,
  id,
  value,
  onChange,
  className,
  invalid,
  money,
}: {
  spec: StageFieldSpec;
  id: string;
  value: StageUiValue;
  onChange: (value: StageUiValue) => void;
  className: string;
  invalid: boolean;
  /** The deals prompt's "$" before an amount. */
  money?: boolean;
}) {
  const aria = invalid ? { 'aria-invalid': true as const } : {};
  const text = Array.isArray(value) ? '' : value;
  switch (spec.kind) {
    case 'textarea':
      return (
        <textarea
          className={cn(className, className === 'lpl-input' ? 'lpl-textarea' : 'lp-x-textarea')}
          id={id}
          rows={3}
          value={text}
          onChange={(e) => onChange(e.target.value)}
          {...aria}
        />
      );
    case 'select':
    case 'owner':
    case 'boolean': {
      const options =
        spec.kind === 'boolean'
          ? [
              { value: 'true', label: 'Yes' },
              { value: 'false', label: 'No' },
            ]
          : spec.options;
      return (
        <select
          className={className}
          id={id}
          value={text}
          onChange={(e) => onChange(e.target.value)}
          {...aria}
        >
          <option value="">Select {spec.label.toLowerCase()}</option>
          {options.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
      );
    }
    case 'multiselect':
      return (
        <select
          className={className}
          id={id}
          multiple
          value={Array.isArray(value) ? value : []}
          onChange={(e) => onChange(Array.from(e.target.selectedOptions).map((o) => o.value))}
          {...aria}
        >
          {spec.options.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
      );
    case 'number':
    case 'currency': {
      const input = (
        <input
          className={className}
          id={id}
          type="number"
          step="any"
          inputMode="decimal"
          min={spec.kind === 'currency' ? 0 : undefined}
          value={text}
          onChange={(e) => onChange(e.target.value)}
          {...aria}
        />
      );
      return money && spec.kind === 'currency' ? (
        <div className="lp-x-money">
          <span aria-hidden="true">$</span>
          {input}
        </div>
      ) : (
        input
      );
    }
    default:
      return (
        <input
          className={className}
          id={id}
          type={
            spec.kind === 'date' ? 'date' : spec.kind === 'datetime' ? 'datetime-local' : 'text'
          }
          autoComplete="off"
          value={text}
          onChange={(e) => onChange(e.target.value)}
          {...aria}
        />
      );
  }
}

/* ------------------------------------------------------- required fields */

export interface StageRequirementsRequest {
  /** `deal`: the deals design's modal; `record`: the Leads design's prompt. */
  variant: 'deal' | 'record';
  recordName: string;
  stageName: string;
  stageColor: string;
  /** The stage's required properties the record has empty. */
  missing: StageFieldSpec[];
  /** Deals' conditional logic: the stage's other (not required) properties, shown filled. */
  optional?: StageFieldSpec[];
  /** Current values of `optional` (stored values, as the record holds them). */
  current?: Record<string, unknown>;
  /** "Leads": the settings path in the Leads prompt's note. */
  plural?: string;
  /**
   * DL2 (deal variant): the record is being created in the stage, not moved there: the intro
   * and the button say so. Off: the move wording, as before.
   */
  creating?: boolean;
  /** Saves the values and makes the move; throws with the message to show. */
  submit: (values: StageValues) => Promise<void>;
}

function StageRequirementsDialog({
  request,
  onDone,
}: {
  request: StageRequirementsRequest;
  onDone: (saved: boolean) => void;
}) {
  const { timeZone } = useUserPrefs();
  const uid = useId();
  const ref = useRef<HTMLDivElement>(null);
  const all = [...request.missing, ...(request.optional ?? [])];
  const required = new Set(request.missing.map((s) => s.name));
  const [ui, setUi] = useState<Record<string, StageUiValue>>(() =>
    Object.fromEntries(
      all.map((s) => [
        s.name,
        required.has(s.name)
          ? toStageUi(s, undefined, timeZone)
          : toStageUi(s, request.current?.[s.name], timeZone),
      ]),
    ),
  );
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [failure, setFailure] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const cancel = () => {
    if (!busy) onDone(false);
  };
  useDialogKeys(ref, cancel);

  const save = async () => {
    if (busy) return;
    const next: Record<string, string> = {};
    for (const spec of all) {
      const r = stageValuesFrom([spec], ui, required, timeZone);
      if ('error' in r) next[spec.name] = r.error;
    }
    setErrors(next);
    const first = all.find((s) => next[s.name]);
    if (first) {
      document.getElementById(`${uid}-${first.name}`)?.focus();
      return;
    }
    const values = stageValuesFrom(all, ui, required, timeZone);
    if ('error' in values) return;
    setBusy(true);
    setFailure(null);
    try {
      await request.submit(values.ok);
      onDone(true);
    } catch (err) {
      setFailure(errorMessage(err));
      setBusy(false);
    }
  };

  const set = (name: string, value: StageUiValue) => {
    setUi((cur) => ({ ...cur, [name]: value }));
    if (errors[name]) {
      setErrors((cur) => Object.fromEntries(Object.entries(cur).filter(([k]) => k !== name)));
    }
  };
  const n = request.missing.length;
  const titleId = `${uid}-title`;

  if (request.variant === 'deal') {
    return (
      <div
        className="lp-modal-ov is-open"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) cancel();
        }}
      >
        <div
          ref={ref}
          className="lp-modal lp-modal--x"
          role="dialog"
          aria-modal="true"
          aria-labelledby={titleId}
        >
          <header className="lp-modal__head">
            <h2 id={titleId}>Required properties for {request.stageName}</h2>
            <button type="button" className="lp-icon-btn" aria-label="Close" onClick={cancel}>
              <CloseIcon />
            </button>
          </header>
          <div className="lp-modal__body">
            <p className="lp-x-intro">
              {request.creating ? 'Creating' : 'Moving'} <strong>{request.recordName}</strong>{' '}
              {request.creating ? 'in' : 'to'} <strong>{request.stageName}</strong> requires these
              properties.
            </p>
            {failure ? (
              <p className="lp-x-err" role="alert">
                {failure}
              </p>
            ) : null}
            {all.map((spec) => {
              const id = `${uid}-${spec.name}`;
              const err = errors[spec.name];
              return (
                <div key={spec.name} className={cn('lp-x-field', err && 'is-invalid')}>
                  <label className="lp-x-label" htmlFor={id}>
                    {spec.label}
                    {required.has(spec.name) ? (
                      <span className="lp-x-req" aria-hidden="true">
                        *
                      </span>
                    ) : null}
                  </label>
                  <StageFieldControl
                    spec={spec}
                    id={id}
                    value={ui[spec.name] ?? ''}
                    onChange={(v) => set(spec.name, v)}
                    className="lp-x-input"
                    invalid={Boolean(err)}
                    money
                  />
                  <p className="lp-x-err" role="alert" hidden={!err}>
                    {err}
                  </p>
                </div>
              );
            })}
          </div>
          <footer className="lp-modal__foot">
            <div className="lp-modal__left" />
            <div className="lp-modal__acts">
              <button
                type="button"
                className="lp-btn lp-btn--primary"
                disabled={busy}
                onClick={() => void save()}
              >
                {request.creating ? 'Save and create' : 'Save and move'}
              </button>
              <button type="button" className="lp-btn lp-btn--outline" onClick={cancel}>
                Cancel
              </button>
            </div>
          </footer>
        </div>
      </div>
    );
  }

  return (
    <div
      className="lpl-ov"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) cancel();
      }}
    >
      <div
        ref={ref}
        className="lpl-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
      >
        <header className="lpl-head">
          <h2 id={titleId}>Complete required fields to move to {request.stageName}</h2>
          <button type="button" className="lpl-x" aria-label="Close" onClick={cancel}>
            <CloseIcon />
          </button>
        </header>
        <div className="lpl-body">
          <p className="lpl-intro">
            <span className="lpl-stage" style={stageStyle(request.stageColor)}>
              {request.stageName}
            </span>{' '}
            requires {n} field{n === 1 ? '' : 's'} that {request.recordName}{' '}
            {n === 1 ? 'is' : 'are'} missing. Fill {n === 1 ? 'it' : 'them'} in to continue.
          </p>
          <ul className="lpl-missing" aria-label="Missing fields">
            {request.missing.map((s) => (
              <li key={s.name}>{s.label}</li>
            ))}
          </ul>
          {failure ? (
            <p className="lpl-err" role="alert">
              {failure}
            </p>
          ) : null}
          {all.map((spec) => {
            const id = `${uid}-${spec.name}`;
            const err = errors[spec.name];
            return (
              <div key={spec.name} className={cn('lpl-field', err && 'is-invalid')}>
                <label className="lpl-label" htmlFor={id}>
                  {spec.label}
                  {required.has(spec.name) ? (
                    <span className="lpl-req" aria-hidden="true">
                      *
                    </span>
                  ) : null}
                </label>
                <StageFieldControl
                  spec={spec}
                  id={id}
                  value={ui[spec.name] ?? ''}
                  onChange={(v) => set(spec.name, v)}
                  className="lpl-input"
                  invalid={Boolean(err)}
                />
                <p className="lpl-err" role="alert" hidden={!err}>
                  {err}
                </p>
              </div>
            );
          })}
          <p className="lpl-note">
            Required fields are set in Settings › Objects › {request.plural ?? 'Objects'} ›
            Pipelines.
          </p>
        </div>
        <footer className="lpl-foot">
          <button
            type="button"
            className="lpl-btn lpl-btn--primary"
            disabled={busy}
            onClick={() => void save()}
          >
            Save and move to {request.stageName}
          </button>
          <button type="button" className="lpl-btn" onClick={cancel}>
            Cancel
          </button>
        </footer>
      </div>
    </div>
  );
}

/** A promise-style dialog: `ask` opens it and resolves when it closes; render `dialog` once. */
function usePromptDialog<R>(render: (request: R, done: (ok: boolean) => void) => ReactNode): {
  ask: (request: R) => Promise<boolean>;
  dialog: ReactNode;
} {
  const [request, setRequest] = useState<R | null>(null);
  const [portal, setPortal] = useState<HTMLElement | null>(null);
  useEffect(() => setPortal(document.body), []);
  const resolver = useRef<((ok: boolean) => void) | null>(null);
  const done = useCallback((ok: boolean) => {
    resolver.current?.(ok);
    resolver.current = null;
    setRequest(null);
  }, []);
  const ask = useCallback(
    (next: R) =>
      new Promise<boolean>((resolve) => {
        resolver.current?.(false);
        resolver.current = resolve;
        setRequest(next);
      }),
    [],
  );
  return {
    ask,
    dialog: request && portal ? createPortal(render(request, done), portal) : null,
  };
}

/** The required-fields prompt. `ask` resolves true once `submit` succeeded. */
export function useStageRequirementsPrompt() {
  return usePromptDialog<StageRequirementsRequest>((request, done) => (
    <StageRequirementsDialog request={request} onDone={done} />
  ));
}
