'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useEscape } from './useDropdown';

/**
 * The design's small text dialog (`.reports-modal`, reports-dashboard.js `openModal`): Create
 * dashboard, Edit dashboard title, Clone dashboard, Rename report. `validate` returns an error
 * shown under the field (#579), or null.
 */
export function TextModal({
  open,
  title,
  message,
  fieldLabel,
  initialValue,
  confirmLabel,
  maxLength,
  validate,
  onConfirm,
  onClose,
}: {
  open: boolean;
  title: string;
  message?: string;
  fieldLabel: string;
  initialValue: string;
  confirmLabel: string;
  maxLength?: number;
  validate?: (value: string) => string | null;
  /** Resolves to an error to show, or nothing when done (the dialog then closes). */
  onConfirm: (value: string) => Promise<string | null | void>;
  onClose: () => void;
}) {
  const [value, setValue] = useState(initialValue);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const input = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (!open) return;
    setValue(initialValue);
    setError(null);
    setBusy(false);
    requestAnimationFrame(() => input.current?.select());
  }, [open, initialValue]);
  useEscape(open, onClose);
  if (!open) return null;

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (busy) return;
    const problem = validate?.(value) ?? null;
    if (problem) {
      setError(problem);
      return;
    }
    setBusy(true);
    try {
      const result = await onConfirm(value.trim());
      if (result) setError(result);
      else onClose();
    } finally {
      setBusy(false);
    }
  };

  return (
    <div
      className="reports-modal-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        className="reports-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="reports-modal-title"
      >
        <header className="reports-modal__header">
          <h2 id="reports-modal-title">{title}</h2>
          <button
            type="button"
            className="reports-modal__close"
            aria-label="Close dialog"
            onClick={onClose}
          >
            ×
          </button>
        </header>
        <div className="reports-modal__form-content">
          {message ? <p>{message}</p> : null}
          <form onSubmit={(e) => void submit(e)} noValidate>
            <label className="reports-modal__field">
              <span>{fieldLabel}</span>
              <input
                ref={input}
                value={value}
                maxLength={maxLength ? maxLength + 50 : undefined}
                aria-invalid={error ? true : undefined}
                aria-describedby={error ? 'reports-modal-error' : undefined}
                onChange={(e) => {
                  setValue(e.target.value);
                  setError(null);
                }}
              />
            </label>
            {error ? (
              <p
                id="reports-modal-error"
                className="crm-fs-8 crm-text-danger crm-mt-1"
                role="alert"
              >
                {error}
              </p>
            ) : null}
            <div className="reports-modal__actions">
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={onClose}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="btn-crm btn-crm--primary btn-crm--sm"
                disabled={busy}
              >
                {confirmLabel}
              </button>
            </div>
          </form>
        </div>
      </section>
    </div>
  );
}

/** The design's "Remove the report … from this dashboard?" dialog (`#reportsRemoveModal`). */
export function RemoveReportModal({
  title,
  onConfirm,
  onClose,
}: {
  /** The report's title; null: closed. */
  title: string | null;
  onConfirm: () => void;
  onClose: () => void;
}) {
  useEscape(title !== null, onClose);
  if (title === null) return null;
  return (
    <div
      className="modal-backdrop reports-remove-modal-backdrop is-open"
      aria-hidden="false"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="modal reports-remove-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="reportsRemoveModalTitle"
      >
        <header className="modal__header reports-remove-modal__header">
          <h2 className="modal__title reports-remove-modal__title" id="reportsRemoveModalTitle">
            Remove the report <span>&quot;{title}&quot;</span> from this dashboard?
          </h2>
          <button type="button" className="modal__close" aria-label="Close modal" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-20" />
          </button>
        </header>
        <div className="modal__body reports-remove-modal__body">
          <p className="reports-remove-modal__text">
            You&apos;re about to remove this report. This will only remove the report from this
            dashboard.
          </p>
        </div>
        <footer className="modal__footer reports-remove-modal__footer">
          <button type="button" className="btn-crm btn-crm--danger" onClick={onConfirm}>
            Remove report
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </div>
    </div>
  );
}

/** "Delete dashboard" confirmation, in the same dialog style as Remove report. */
export function DeleteDashboardModal({
  name,
  busy,
  onConfirm,
  onClose,
}: {
  name: string | null;
  busy: boolean;
  onConfirm: () => void;
  onClose: () => void;
}) {
  useEscape(name !== null, onClose);
  if (name === null) return null;
  return (
    <div
      className="modal-backdrop reports-remove-modal-backdrop is-open"
      aria-hidden="false"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="modal reports-remove-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="reportsDeleteDashboardTitle"
      >
        <header className="modal__header reports-remove-modal__header">
          <h2 className="modal__title reports-remove-modal__title" id="reportsDeleteDashboardTitle">
            Delete the dashboard <span>&quot;{name}&quot;</span>?
          </h2>
          <button type="button" className="modal__close" aria-label="Close modal" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-20" />
          </button>
        </header>
        <div className="modal__body reports-remove-modal__body">
          <p className="reports-remove-modal__text">
            The dashboard, its notes and its scheduled emails are deleted for everyone. This
            can&apos;t be undone.
          </p>
        </div>
        <footer className="modal__footer reports-remove-modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--danger"
            disabled={busy}
            onClick={onConfirm}
          >
            Delete dashboard
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </div>
    </div>
  );
}

/**
 * "Move report" / "Add to dashboard" (the design's `.reports-action-modal--move`): pick another
 * dashboard the caller may change.
 */
export function PickDashboardModal({
  open,
  mode,
  options,
  onConfirm,
  onClose,
}: {
  open: boolean;
  mode: 'move' | 'add';
  options: Array<{ id: string; name: string }>;
  onConfirm: (dashboardId: string) => Promise<void>;
  onClose: () => void;
}) {
  const [choice, setChoice] = useState('');
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (open) {
      setChoice('');
      setBusy(false);
    }
  }, [open]);
  useEscape(open, onClose);
  if (!open) return null;
  return (
    <div
      className="reports-action-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        className="reports-action-modal reports-action-modal--move"
        role="dialog"
        aria-modal="true"
        aria-labelledby="reports-action-title"
      >
        <header className="reports-action-modal__header">
          <h2 id="reports-action-title">{mode === 'move' ? 'Move report' : 'Add to dashboard'}</h2>
          <button
            type="button"
            className="reports-action-close"
            aria-label="Close dialog"
            onClick={onClose}
          >
            ×
          </button>
        </header>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            if (!choice || busy) return;
            setBusy(true);
            void onConfirm(choice).finally(() => setBusy(false));
          }}
        >
          <label className="reports-action-field">
            <span>Select existing dashboard</span>
            <select
              className="input"
              value={choice}
              onChange={(e) => setChoice(e.target.value)}
              aria-label="Select existing dashboard"
            >
              <option value="">Select dashboard</option>
              {options.map((o) => (
                <option key={o.id} value={o.id}>
                  {o.name}
                </option>
              ))}
            </select>
            {options.length === 0 ? (
              <small className="reports-action-error">
                There is no other dashboard you can change.
              </small>
            ) : null}
          </label>
          <div className="reports-action-warning">
            Adding reports to a dashboard will change who has access to it.{' '}
            <strong>The reports will take on the dashboard&apos;s access rules.</strong>
          </div>
          <footer className="reports-action-modal__footer">
            <button
              type="submit"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={!choice || busy}
            >
              {mode === 'move' ? 'Move' : 'Add to dashboard'}
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={onClose}
            >
              Cancel
            </button>
          </footer>
        </form>
      </section>
    </div>
  );
}

/** The design's "Edit content" dialog for a note widget (`#reportsAuditEditModal`). */
export function NoteModal({
  open,
  heading,
  initialTitle,
  initialText,
  onSave,
  onClose,
}: {
  open: boolean;
  heading: string;
  initialTitle: string;
  initialText: string;
  onSave: (title: string, text: string) => Promise<boolean>;
  onClose: () => void;
}) {
  const [title, setTitle] = useState(initialTitle);
  const [text, setText] = useState(initialText);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (!open) return;
    setTitle(initialTitle);
    setText(initialText);
    setError(null);
    setBusy(false);
  }, [open, initialTitle, initialText]);
  useEscape(open, onClose);
  if (!open) return null;
  const save = async () => {
    if (!text.trim()) {
      setError('Enter note text first.');
      return;
    }
    setBusy(true);
    const ok = await onSave(title.trim(), text);
    setBusy(false);
    if (ok) onClose();
  };
  return (
    <div
      className="modal-backdrop reports-audit-edit-modal-backdrop is-open"
      aria-hidden="false"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="modal reports-audit-edit-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="reportsAuditEditModalTitle"
      >
        <header className="modal__header">
          <h2 className="modal__title" id="reportsAuditEditModalTitle">
            {heading}
          </h2>
          <button type="button" className="modal__close" aria-label="Close modal" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-20" />
          </button>
        </header>
        <div className="modal__body">
          <div className="crm-mb-3">
            <label
              htmlFor="reportsAuditEditTitle"
              className="crm-form-label crm-fw-semibold crm-fs-7 crm-mb-1"
            >
              Title
            </label>
            <input
              type="text"
              id="reportsAuditEditTitle"
              className="reports-audit-edit-input form-control crm-w-100"
              autoComplete="off"
              maxLength={191}
              placeholder="Dashboard note"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </div>
          <div className="crm-mb-2">
            <label
              htmlFor="reportsAuditEditText"
              className="crm-form-label crm-fw-semibold crm-fs-7 crm-mb-0"
            >
              Content
            </label>
            <p className="crm-fs-8 crm-text-muted crm-mb-2">Add text for your team.</p>
            <textarea
              id="reportsAuditEditText"
              className="input crm-w-100"
              rows={8}
              maxLength={20000}
              placeholder="Start typing to leave a note..."
              value={text}
              onChange={(e) => {
                setText(e.target.value);
                setError(null);
              }}
              style={{ height: 'auto', minHeight: 160, paddingTop: 10 }}
            />
            {error ? (
              <p className="crm-fs-8 crm-text-danger crm-mt-1" role="alert">
                {error}
              </p>
            ) : null}
          </div>
        </div>
        <footer className="modal__footer crm-d-flex crm-align-items-center crm-gap-3 crm-justify-content-start">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy}
            onClick={() => void save()}
          >
            Save changes
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </div>
    </div>
  );
}
