'use client';

/**
 * IDB4c: putting an import's records in a segment (a static list). The runner (a new segment named
 * by the import list's rule, then the records added) is shared by Import details' dialog (the
 * design's `import-details.php:1976-2001`) and the hub's (`rowDialogs.tsx` `SegmentDialog`).
 * Decisions: `batches/IDB4c-import-segments.md`.
 */
import { useEffect, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { startBulk, type BulkObject } from '@/features/bulk/api.client';
import { ensureImportList } from '@/features/imports/api.client';
import {
  addListMembers,
  createList,
  deleteList,
  listAllLists,
  type CrmList,
} from '@/features/lists/api.client';
import { errorText, isApiError } from '@/lib/api/errors';
import { followBulk } from '../bulkFollow';
import { outcomeOfOperation, type BulkOutcome } from '../importBulk';
import {
  detailsSegmentOptions,
  memberChunks,
  segmentAddedToast,
  segmentListName,
} from '../importSegment';
import { DesignModal } from './DesignModal';

/** What goes in the segment: the import's records (by the import filter), or checked rows. */
export type SegmentSource = { kind: 'import'; importId: string } | { kind: 'ids'; ids: string[] };

export interface SegmentNaming {
  importName: string | null;
  fileName: string;
}

const NAME_TRIES = 20;
const BULK_OBJECTS = new Set(['contact', 'company', 'deal']);

/**
 * A new static segment named as the import's list (" (n)" when the name is taken: the API's
 * 409, names are unique across the business, `lists/service.ts:169-175`).
 */
export async function createNamedSegment(
  naming: SegmentNaming,
  objectType: string,
): Promise<CrmList> {
  for (let n = 1; n <= NAME_TRIES; n++) {
    try {
      return await createList({
        name: segmentListName(naming.importName, naming.fileName, n),
        objectType,
        listType: 'static',
      });
    } catch (err) {
      if (!(isApiError(err) && err.isConflict)) throw err;
    }
  }
  throw new Error('No free segment name for this import. Rename a segment and try again.');
}

/**
 * Adds the records: an import's by the bulk job's import filter (contacts, companies, deals;
 * `POST /{object}/bulk` `add_to_list`), checked rows 100 a call (`POST /lists/:id/members`).
 * Null when the page went before the job ended.
 */
export async function addToSegment(
  listId: string,
  objectType: string,
  source: SegmentSource,
  isAlive: () => boolean,
): Promise<BulkOutcome | null> {
  if (source.kind === 'import') {
    const op = await startBulk(objectType as BulkObject, {
      action: 'add_to_list',
      listId,
      selection: { query: { importId: source.importId } },
    });
    const end = await followBulk(op, isAlive);
    if (end.kind === 'stopped') return null;
    if (end.kind === 'lost') return { ok: 0, failed: 0, error: end.error };
    return outcomeOfOperation(end.op);
  }
  let ok = 0;
  let failed = 0;
  let last: unknown = null;
  for (const chunk of memberChunks(source.ids)) {
    try {
      const res = await addListMembers(listId, chunk);
      ok += res.changed + res.unchanged;
    } catch (err) {
      // Review: the API refuses a whole call for one id it can't find or show (400, as the bulk
      // job retries one at a time, `bulk-operations/service.ts:369-375`).
      if (!(isApiError(err) && err.status === 400) || chunk.length === 1) {
        failed += chunk.length;
        last = err;
        continue;
      }
      for (const id of chunk) {
        try {
          const res = await addListMembers(listId, [id]);
          ok += res.changed + res.unchanged;
        } catch (one) {
          failed += 1;
          last = one;
        }
      }
    }
  }
  return { ok, failed, error: ok === 0 && last ? errorText(last) : null };
}

/** Whether an import's records can go in a segment by the import filter (the bulk job's objects). */
export function importSegmentable(objectType: string): boolean {
  return BULK_OBJECTS.has(objectType);
}

/**
 * "View contacts segment": the import's live list (`POST /imports/:id/list`), then its page. The
 * design goes there by `location` too (`import-details.js:747-748`). Returns the API's message
 * when it can't (409: running, or no linked records).
 */
export async function openImportSegment(importId: string): Promise<string | null> {
  try {
    const { listId } = await ensureImportList(importId);
    window.location.assign(`/lists/${listId}`);
    return null;
  } catch (err) {
    return errorText(err);
  }
}

/**
 * "Add imported contacts to segment" on Import details (`import-details.php:1976-2001`): the
 * design's choices with the business's static segments of the object; New active segment is
 * coming soon (decision B). The bar's Add to static segment opens it for the checked rows.
 */
export function ImportSegmentDialog({
  open,
  count,
  noun,
  objectType,
  source,
  naming,
  onClose,
  onDone,
}: {
  open: boolean;
  count: number;
  /** "contacts" */
  noun: string;
  objectType: string;
  source: SegmentSource;
  naming: SegmentNaming;
  onClose: () => void;
  /** After records were added (the page may reload). */
  onDone?: () => void;
}) {
  const toast = useToast();
  const [lists, setLists] = useState<CrmList[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [pick, setPick] = useState('new_active');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const mounted = useRef(true);
  useEffect(
    () => () => {
      mounted.current = false;
    },
    [],
  );
  useEffect(() => {
    if (!open) return;
    setPick('new_active');
    setError(null);
    setLists(null);
    setLoadError(null);
    let live = true;
    listAllLists().then(
      (res) => {
        if (live) setLists(res.lists);
      },
      (err: unknown) => {
        if (live) setLoadError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [open]);
  if (!open) return null;

  const add = async () => {
    // The design closes after Add (js:626-629).
    if (pick === 'new_active') {
      onClose();
      toast('New active segment is coming soon', 'info');
      return;
    }
    setBusy(true);
    setError(null);
    let listId = pick;
    let made: CrmList | null = null;
    try {
      if (pick === 'new_static') {
        made = await createNamedSegment(naming, objectType);
        listId = made.id;
      }
    } catch (err) {
      setBusy(false);
      setError(errorText(err));
      return;
    }
    if (source.kind === 'import') {
      // The job runs on: the dialog closes and its result comes as a toast.
      setBusy(false);
      onClose();
      let outcome: BulkOutcome | null = null;
      try {
        outcome = await addToSegment(listId, objectType, source, () => mounted.current);
      } catch (err) {
        outcome = { ok: 0, failed: 0, error: errorText(err) };
      }
      // Review: a segment made here that got nothing is taken back, not left empty.
      if (made && outcome && outcome.ok === 0) void deleteList(made.id).catch(() => {});
      if (outcome && mounted.current) {
        const t = segmentAddedToast(noun, outcome);
        toast(t.text, t.tone);
        onDone?.();
      }
      return;
    }
    try {
      const outcome = await addToSegment(listId, objectType, source, () => true);
      if (outcome?.error && outcome.ok === 0) {
        // Review: a segment made here stays picked, so Add again uses it (no "(2)" copy).
        if (made) {
          const kept = made;
          setLists((cur) => [...(cur ?? []), kept]);
          setPick(kept.id);
        }
        setError(outcome.error);
        return;
      }
      onClose();
      if (outcome) {
        const t = segmentAddedToast(noun, outcome);
        toast(t.text, t.tone);
      }
      onDone?.();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };
  // Review: the footer's Close waits for a running add too, as × and Escape.
  const close = () => {
    if (!busy) onClose();
  };

  return (
    <DesignModal
      id="modalAddSegment"
      title={`Add imported ${noun} to segment`}
      footerClass="crm-justify-content-end"
      onClose={close}
      footer={
        <>
          <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
            Close
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy || (pick !== 'new_active' && pick !== 'new_static' && !lists)}
            onClick={() => void add()}
          >
            Add
          </button>
        </>
      }
    >
      <div className="field crm-mb-4">
        <label className="field__label" htmlFor="segmentTargetSelect">
          Add <strong data-selected-count-label="">{count.toLocaleString('en-US')}</strong> imported{' '}
          {noun} to
        </label>
        <CustomSelect
          id="segmentTargetSelect"
          className="crm-w-100"
          placeholder="New active segment"
          searchable={false}
          value={pick}
          options={detailsSegmentOptions(lists ?? [], objectType)}
          onChange={setPick}
        />
      </div>
      <p className="crm-text-muted crm-fs-7 crm-m-0">
        Create a contacts segment which automatically updates their contacts based on its criteria.{' '}
        <a
          href="#"
          className="crm-link crm-d-inline-flex crm-align-items-center crm-gap-1"
          onClick={(e) => {
            e.preventDefault();
            toast('Segments documentation is coming soon', 'info');
          }}
        >
          <span>Learn more</span>
          <CrmIcon name="external" className="iconSize-14" />
        </a>
      </p>
      {loadError ? <Alert tone="danger">{loadError}</Alert> : null}
      {error ? <Alert tone="danger">{error}</Alert> : null}
    </DesignModal>
  );
}
