'use client';

/**
 * The row menu's dialogs (DI-1b) with the design's markup and classes: "Add imported contacts to
 * segment" (`data-integration.php:1819-1845`) and the "Restore CRM changes" drawer (`:1847-1984`,
 * in `RestoreDrawer.tsx` since QA #553, when it began to preview and restore for real).
 */
import { useEffect, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { getImportRun } from '@/features/imports/api.client';
import { errorText } from '@/lib/api/errors';
import { deleteList } from '@/features/lists/api.client';
import type { BulkOutcome } from '../importBulk';
import { hubSegmentToast } from '../importSegment';
import { addToSegment, createNamedSegment } from './ImportSegment';
import { SEGMENT_OPTIONS, segmentCountText } from '../restore';

/** IDB4c: the hub's New static segment, from the import's own name and file. */
async function addImportToNewSegment(
  importId: string,
): Promise<{ text: string; tone: 'success' | 'info' | 'danger' }> {
  try {
    const run = await getImportRun(importId);
    const list = await createNamedSegment(
      { importName: run.name ?? null, fileName: run.fileName },
      run.objectType,
    );
    let outcome: BulkOutcome | null;
    try {
      outcome = await addToSegment(
        list.id,
        run.objectType,
        { kind: 'import', importId },
        () => true,
      );
    } catch (err) {
      outcome = { ok: 0, failed: 0, error: errorText(err) };
    }
    // Review: the segment made here is taken back when nothing went in.
    if (outcome && outcome.ok === 0) void deleteList(list.id).catch(() => {});
    return outcome
      ? hubSegmentToast(run.fileName, outcome)
      : { text: 'Adding to the segment stopped', tone: 'info' };
  } catch (err) {
    return { text: errorText(err), tone: 'danger' };
  }
}

/**
 * "Add imported contacts to segment": Add stays off until a kind is picked (`:1839`). IDB4c: for a
 * contact import, New static segment makes the segment (named as the import's list) and adds the
 * import's contacts by the bulk job; the toast is the design's (`data-integration.js:659`) with
 * what was added. Existing static and New active stay "coming soon": the design picks no segment
 * there (`:653-659`), and active segments are out (decision B).
 */
export function SegmentDialog({
  open,
  total,
  importId = null,
  objectType = null,
  onSoon,
  onClose,
}: {
  open: boolean;
  /** The import's created and updated records. */
  total: number;
  /** IDB4c: the import, for New static segment. */
  importId?: string | null;
  objectType?: string | null;
  onSoon: (label: string) => void;
  onClose: () => void;
}) {
  const toast = useToast();
  const [kind, setKind] = useState('');
  // Each open starts with no pick (`resetSelection`, `data-integration.js:590-608`).
  useEffect(() => {
    if (open) setKind('');
  }, [open]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div
      className="modal-backdrop is-open"
      id="diAddSegmentModal"
      aria-hidden="false"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="modal di-add-segment-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="diAddSegmentTitle"
      >
        <div className="modal__header">
          <h2 className="modal__title" id="diAddSegmentTitle">
            Add imported contacts to segment
          </h2>
          <button
            type="button"
            className="modal__close"
            aria-label="Close dialog"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </div>
        <div className="modal__body">
          <label
            className="field__label crm-fw-medium crm-mb-2 crm-d-block"
            htmlFor="diSegmentSelect"
          >
            Add <span id="diSegmentContactsCount">{segmentCountText(total)}</span> imported contacts
            to:
          </label>
          <CustomSelect
            id="diSegmentSelect"
            className="crm-w-100"
            placeholder="Select"
            value={kind}
            options={[...SEGMENT_OPTIONS]}
            onChange={setKind}
          />
        </div>
        <div className="modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="diAddSegmentSubmitBtn"
            disabled={!kind}
            onClick={() => {
              // The design closes the dialog after Add (`data-integration.js:656-662`).
              onClose();
              if (kind === 'new-static' && importId && objectType === 'contact') {
                void addImportToNewSegment(importId).then((t) => toast(t.text, t.tone));
                return;
              }
              onSoon('Add imported contacts to segment');
            }}
          >
            Add
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

/** QA #553: the drawer moved to its own file; imported from here as before. */
export { RestoreDrawer } from './RestoreDrawer';
