'use client';

/**
 * IDB4b: the records tab's bulk bar, its dialogs (the design's markup, `import-details.php`
 * :921-1534, :1874-2144) and the design's inline editors (`import-details.js:941-1226`). The
 * dialogs run the bulk calls the lists use; Create tasks and Create leads are the Contacts
 * list's panels, Enroll in sequence and workflow master's dialogs (decisions:
 * `batches/IDB4b-import-bulk-edit.md`).
 */
import { useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { startBulk, type BulkObject, type BulkOperation } from '@/features/bulk/api.client';
import {
  BulkActionsBar,
  bulkEditValues,
  type BulkRequest,
} from '@/features/bulk/ui/BulkActionsBar';
import {
  DesignBulkPanels,
  MultiPick,
  type BulkPanel,
  type BxRecord,
  type PickOption,
  type ShareInput,
} from '@/features/bulk/ui/DesignBulkPanels';
import type { ImportObjectType } from '@/features/imports/types';
import { LpIcon, type LpIconName } from '@/features/list-page/ui/LpIcon';
import { listTeamOptions } from '@/features/members/api.client';
import { listAllOwners } from '@/features/owners/api.client';
import { bulkObjectRecords, listLinkedRecords, unlinkRecords } from '@/features/objects/api.client';
import { errorText } from '@/lib/api/errors';
import { followBulk } from '../bulkFollow';
import { DesignModal } from './DesignModal';
import { ImportSegmentDialog, type SegmentNaming } from './ImportSegment';
import { cn } from '@/lib/utils/cn';
import {
  assignCall,
  assocCountText,
  assocKey,
  assocLabelOptions,
  assocShown,
  associatedText,
  bulkBar,
  bulkCountText,
  bulkResultToast,
  deleteCall,
  deleteConfirmOk,
  editCall,
  editValueError,
  editValueKind,
  outcomeOfObjects,
  outcomeOfOperation,
  shareCall,
  subscriptionsCall,
  type AssocGroup,
  type BulkAct,
  type BulkCall,
  type BulkDone,
  type BulkItem,
  type EditField,
} from '../importBulk';

// ── The bar ─────────────────────────────────────────────────────────────────────────────────

const ICONS: Partial<Record<BulkAct, LpIconName>> = {
  enrich: 'sparkle',
  'fill-smart': 'sparkle',
  assign: 'arrowRight',
  share: 'share',
  edit: 'pencil',
  delete: 'trash',
  'review-associations': 'assoc',
  'create-tasks': 'plus',
  'enroll-sequence': 'sequence',
  'create-leads': 'plus',
  'enroll-agent': 'sparkles',
  'check-enrichment': 'sparkle',
  'add-segment': 'segment',
  'enroll-workflow': 'workflow',
  'power-dialer': 'dialer',
};
const CRM_ICONS: Partial<Record<BulkAct, string>> = {
  'legal-basis': 'file',
  'edit-subscriptions': 'mail',
  'opt-in-status': 'check-circle',
};

function ActIcon({ act, menu }: { act: BulkAct; menu: boolean }) {
  const lp = ICONS[act];
  if (lp) return <LpIcon name={lp} className={menu ? 'iconSize-14' : undefined} />;
  const crm = CRM_ICONS[act];
  return crm ? <CrmIcon name={crm} className="iconSize-14" /> : null;
}

/** The selection bar (`import-details.php:921-1012`); shown while rows are checked. */
export function ImportBulkBar({
  objectType,
  plural,
  count,
  rights,
  moreOpen,
  onToggleMore,
  onAct,
  onClear,
}: {
  objectType: ImportObjectType;
  plural: string;
  count: number;
  rights: { delete: boolean; share: boolean };
  moreOpen: boolean;
  onToggleMore: () => void;
  onAct: (item: BulkItem) => void;
  onClear: () => void;
}) {
  const bar = bulkBar(objectType, rights);
  return (
    <div className="lp-bulk" data-bulk-bar="">
      <div className="lp-bulk__left">
        <strong data-bulk-count="">{bulkCountText(objectType, plural, count)}</strong>
      </div>
      <div className="lp-bulk__acts">
        {bar.primary.map((item) => (
          <button
            key={item.act}
            type="button"
            className={cn('lp-bulkbtn', item.danger && 'lp-bulkbtn--danger')}
            data-bulk-act={item.act}
            disabled={item.disabled}
            onClick={() => onAct(item)}
          >
            <ActIcon act={item.act} menu={false} />
            <span>{item.label}</span>
          </button>
        ))}
        {bar.more.length ? (
          <div className="dropdown" data-dropdown="">
            <button
              type="button"
              className="lp-bulkbtn"
              aria-expanded={moreOpen}
              aria-haspopup="menu"
              onClick={onToggleMore}
            >
              <span>More</span>
              <CrmIcon name="chevron-down" className="lp-i" />
            </button>
            {moreOpen ? (
              <div className="dropdown__menu dropdown__menu--right di-bulk-more-menu" role="menu">
                {bar.more.map((item) => (
                  <button
                    key={item.act}
                    type="button"
                    className="dropdown__item"
                    data-bulk-act={item.act}
                    role="menuitem"
                    onClick={() => onAct(item)}
                  >
                    <ActIcon act={item.act} menu />
                    <span>{item.label}</span>
                  </button>
                ))}
              </div>
            ) : null}
          </div>
        ) : null}
      </div>
      <button
        type="button"
        className="lp-icon-btn lp-bulk__x"
        aria-label="Clear selection"
        onClick={onClear}
      >
        <CrmIcon name="x" className="lp-i" />
      </button>
    </div>
  );
}

// ── Dialogs ─────────────────────────────────────────────────────────────────────────────────

/** The design's "Learn more …" links (`data-soon`): "… is coming soon". */
function LearnMore({ label, soon }: { label: string; soon: string }) {
  const toast = useToast();
  return (
    <a
      href="#"
      className="crm-link crm-d-inline-flex crm-align-items-center crm-gap-1"
      onClick={(e) => {
        e.preventDefault();
        toast(`${soon} is coming soon`, 'info');
      }}
    >
      <span>{label}</span>
      <CrmIcon name="external" className="iconSize-14" />
    </a>
  );
}

const Count = ({ n }: { n: number }) => <span data-selected-count-label="">{n}</span>;

/** "Bulk assign N records" (`import-details.php:1874-1900`). */
export function AssignDialog({
  open,
  count,
  singular,
  owners,
  loadError,
  error,
  busy,
  onClose,
  onAssign,
}: {
  open: boolean;
  count: number;
  /** "Contact" → "Contact owner". */
  singular: string;
  /** The members as "Name (email)"; null while loading. */
  owners: CustomSelectOption[] | null;
  loadError: string | null;
  /** Why the last start failed. */
  error: string | null;
  busy: boolean;
  onClose: () => void;
  onAssign: (ownerId: string | null, name: string | null) => void;
}) {
  const [owner, setOwner] = useState('');
  useEffect(() => {
    if (open) setOwner('');
  }, [open]);
  if (!open) return null;
  const options = [{ value: '', label: 'No owner' }, ...(owners ?? [])];
  return (
    <DesignModal
      id="modalBulkAssign"
      title={
        <>
          Bulk assign <Count n={count} /> records
        </>
      }
      footerClass="crm-justify-content-end"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy || owners === null}
            onClick={() => {
              const picked = owners?.find((o) => o.value === owner);
              onAssign(owner || null, picked ? picked.label.replace(/ \([^)]*\)$/, '') : null);
            }}
          >
            Assign
          </button>
        </>
      }
    >
      <p className="crm-text-muted crm-mb-4">
        Assign the user responsible for managing this record as its owner.{' '}
        <LearnMore label="Learn more about owners" soon="Owners documentation" />
      </p>
      <div className="field crm-mb-4">
        <label className="field__label" htmlFor="bulkAssignOwnerSelect">
          {singular} owner
        </label>
        <CustomSelect
          id="bulkAssignOwnerSelect"
          className="crm-w-100"
          placeholder="Search owner"
          searchPlaceholder="Search owner"
          value={owner}
          options={options}
          onChange={setOwner}
        />
      </div>
      {loadError ? <Alert tone="danger">{loadError}</Alert> : null}
      {error ? <Alert tone="danger">{error}</Alert> : null}
    </DesignModal>
  );
}

function Radios({
  name,
  what,
  mode,
  onMode,
}: {
  name: string;
  what: string;
  mode: 'append' | 'replace';
  onMode: (m: 'append' | 'replace') => void;
}) {
  return (
    <div className="crm-d-flex crm-flex-column crm-gap-2 crm-mt-2">
      {(['append', 'replace'] as const).map((m) => (
        <label key={m} className="check">
          <input
            type="radio"
            name={name}
            value={m}
            checked={mode === m}
            onChange={() => onMode(m)}
          />
          <span className="check__box check__box--radio" />
          <span className="crm-text-dark">
            {m === 'append' ? 'Append to current' : 'Replace current'} {what}
          </span>
        </label>
      ))}
    </div>
  );
}

/** "Share N contacts" (`import-details.php:1903-1973`), with the tab's noun. */
export function ShareDialog({
  open,
  count,
  plural,
  error,
  busy,
  onClose,
  onShare,
}: {
  open: boolean;
  count: number;
  plural: string;
  error: string | null;
  busy: boolean;
  onClose: () => void;
  onShare: (input: ShareInput) => void;
}) {
  const [users, setUsers] = useState<string[]>([]);
  const [teams, setTeams] = useState<string[]>([]);
  const [userMode, setUserMode] = useState<'append' | 'replace'>('append');
  const [teamMode, setTeamMode] = useState<'append' | 'replace'>('append');
  const [people, setPeople] = useState<PickOption[] | null>(null);
  const [teamOptions, setTeamOptions] = useState<PickOption[] | null>(null);
  const [peopleFailed, setPeopleFailed] = useState(false);
  const [teamsFailed, setTeamsFailed] = useState(false);
  useEffect(() => {
    if (!open) return;
    setUsers([]);
    setTeams([]);
    setUserMode('append');
    setTeamMode('append');
    // A failed load is tried again on each open (review), as master's dialog.
    setPeople(null);
    setTeamOptions(null);
    setPeopleFailed(false);
    setTeamsFailed(false);
    let live = true;
    // As master's share dialog (`DesignBulkPanels.tsx:1700-1718`): active members, the teams.
    listAllOwners(false).then(
      (all) => {
        if (live)
          setPeople(
            all.filter((o) => o.active).map((o) => ({ value: o.userId, label: o.name || o.email })),
          );
      },
      () => {
        if (live) setPeopleFailed(true);
      },
    );
    listTeamOptions().then(
      (res) => {
        if (live) setTeamOptions(res.data.map((t) => ({ value: t.id, label: t.name })));
      },
      () => {
        if (live) setTeamsFailed(true);
      },
    );
    return () => {
      live = false;
    };
  }, [open]);
  if (!open) return null;
  const can =
    users.length > 0 || teams.length > 0 || userMode === 'replace' || teamMode === 'replace';
  return (
    <DesignModal
      id="modalBulkShare"
      title={
        <>
          Share <Count n={count} /> {plural}
        </>
      }
      footerClass="crm-justify-content-end"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!can || busy}
            onClick={() => onShare({ userIds: users, teamIds: teams, userMode, teamMode })}
          >
            Share
          </button>
        </>
      }
    >
      <p className="crm-text-muted crm-mb-4">
        Let users and teams access these {plural} based on their permissions.{' '}
        <LearnMore label="Learn more about record sharing" soon="Record sharing documentation" />
      </p>
      <div className="field crm-mb-4">
        <label
          className="field__label crm-d-flex crm-align-items-center crm-gap-1"
          htmlFor="shareUsersSelect"
        >
          <span>Shared users</span>
          <CrmIcon name="info" className="iconSize-14 crm-text-muted" />
        </label>
        <MultiPick
          id="shareUsersSelect"
          label="Shared users"
          options={people}
          failed={peopleFailed ? "Couldn't load users" : null}
          picked={users}
          onChange={setUsers}
          none="No user"
          many="users"
        />
        <Radios name="share_user_mode" what="shared users" mode={userMode} onMode={setUserMode} />
      </div>
      <div className="field crm-mb-3">
        <label
          className="field__label crm-d-flex crm-align-items-center crm-gap-1"
          htmlFor="shareTeamsSelect"
        >
          <span>Shared teams</span>
          <CrmIcon name="info" className="iconSize-14 crm-text-muted" />
        </label>
        <MultiPick
          id="shareTeamsSelect"
          label="Shared teams"
          options={teamOptions}
          failed={teamsFailed ? "Couldn't load teams" : null}
          picked={teams}
          onChange={setTeams}
          none="No team"
          many="teams"
        />
        <Radios name="share_team_mode" what="shared teams" mode={teamMode} onMode={setTeamMode} />
      </div>
      {error ? <Alert tone="danger">{error}</Alert> : null}
    </DesignModal>
  );
}

/** "Bulk edit N records" (`import-details.php:2081-2121`, js:429-443, :544-596). */
export function EditDialog({
  open,
  count,
  properties,
  error,
  busy,
  onClose,
  onUpdate,
}: {
  open: boolean;
  count: number;
  /** Null while loading. */
  properties: EditField[] | null;
  error: string | null;
  busy: boolean;
  onClose: () => void;
  onUpdate: (field: EditField, raw: string) => void;
}) {
  const [key, setKey] = useState('');
  const [value, setValue] = useState('');
  useEffect(() => {
    if (open) {
      setKey('');
      setValue('');
    }
  }, [open]);
  if (!open) return null;
  const field = properties?.find((p) => p.key === key) ?? null;
  const kind = field ? editValueKind(field) : 'text';
  return (
    <DesignModal
      id="modalBulkEdit"
      title={
        <>
          Bulk edit <Count n={count} /> records
        </>
      }
      footerClass="crm-justify-content-end"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="bulkEditSaveBtn"
            disabled={!field || busy}
            onClick={() => field && onUpdate(field, value)}
          >
            Update
          </button>
        </>
      }
    >
      <div className="field crm-mb-4">
        <label className="field__label" htmlFor="bulkEditPropSelect">
          Property to update
        </label>
        <CustomSelect
          id="bulkEditPropSelect"
          className="crm-w-100"
          placeholder="Select a property to edit"
          value={key}
          options={(properties ?? []).map((p) => ({ value: p.key, label: p.label }))}
          onChange={(k) => {
            setKey(k);
            setValue('');
          }}
        />
      </div>
      {field ? (
        <div className="field crm-mb-3" id="bulkEditValueWrap">
          <label className="field__label" htmlFor="bulkEditValueInput">
            New value
          </label>
          <div id="bulkEditValueControl">
            {kind === 'select' ? (
              <CustomSelect
                id="bulkEditValueInput"
                className="crm-w-100"
                placeholder="-- Clear value --"
                value={value}
                options={[{ value: '', label: '-- Clear value --' }, ...(field.options ?? [])]}
                onChange={setValue}
              />
            ) : (
              <input
                type={kind === 'date' ? 'date' : 'text'}
                className="input crm-w-100"
                id="bulkEditValueInput"
                placeholder="Enter new value"
                inputMode={field.type === 'number' ? 'decimal' : undefined}
                value={value}
                onChange={(e) => setValue(e.target.value)}
              />
            )}
          </div>
          <p className="crm-text-muted crm-fs-7 crm-m-0">
            Leave the value empty to clear the property.
          </p>
        </div>
      ) : null}
      {properties === null ? <p className="crm-text-muted crm-m-0">Loading properties…</p> : null}
      {error ? <Alert tone="danger">{error}</Alert> : null}
    </DesignModal>
  );
}

/** "Delete N records?" (`import-details.php:2124-2144`, js:421-428, :530-541). */
export function DeleteDialog({
  open,
  count,
  error,
  busy,
  onClose,
  onDelete,
}: {
  open: boolean;
  count: number;
  error: string | null;
  busy: boolean;
  onClose: () => void;
  onDelete: () => void;
}) {
  const [typed, setTyped] = useState('');
  useEffect(() => {
    if (open) setTyped('');
  }, [open]);
  if (!open) return null;
  return (
    <DesignModal
      id="modalBulkDelete"
      title={
        <>
          Delete <Count n={count} /> records?
        </>
      }
      footerClass="crm-justify-content-start crm-gap-3"
      onClose={onClose}
      footer={
        <>
          <button
            type="button"
            className="btn-crm btn-crm--danger"
            id="bulkDeleteConfirmBtn"
            disabled={!deleteConfirmOk(typed, count) || busy}
            onClick={onDelete}
          >
            Delete
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </>
      }
    >
      <p className="crm-text-muted crm-mb-2">
        You’re about to delete <strong data-selected-count-label="">{count}</strong> records.
        Deleted records can’t be restored after 90 days.
      </p>
      <p className="crm-text-muted crm-mb-4">
        Records created after this submission will not be deleted.
      </p>
      <div className="field crm-mb-2">
        <label className="field__label" htmlFor="deleteConfirmCountInput">
          Type the number of records below to delete
        </label>
        <input
          type="text"
          className="input crm-w-100"
          id="deleteConfirmCountInput"
          placeholder={String(count)}
          autoComplete="off"
          inputMode="numeric"
          value={typed}
          onChange={(e) => setTyped(e.target.value)}
        />
      </div>
      {error ? <Alert tone="danger">{error}</Alert> : null}
    </DesignModal>
  );
}

/** "Review Associations" (`import-details.php:2004-2078`, js:654-699) on the records' links. */
export function ReviewAssociationsDialog({
  open,
  groups,
  loadError,
  types,
  busy,
  onClose,
  onDissociate,
}: {
  open: boolean;
  /** Null while loading. */
  groups: AssocGroup[] | null;
  loadError: string | null;
  types: Array<{ type: string; plural: string }>;
  busy: boolean;
  onClose: () => void;
  /** The checked links (`assocKey`). */
  onDissociate: (keys: string[]) => void;
}) {
  const [type, setType] = useState('all');
  const [label, setLabel] = useState('all');
  const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
  const [checked, setChecked] = useState<Set<string>>(new Set());
  useEffect(() => {
    if (open) {
      setType('all');
      setLabel('all');
      setCollapsed(new Set());
      setChecked(new Set());
    }
  }, [open]);
  // Links that left (dissociated) are no longer checked.
  useEffect(() => setChecked(new Set()), [groups]);
  const shown = useMemo(() => assocShown(groups ?? [], type, label), [groups, type, label]);
  if (!open) return null;
  const shownKeys = shown.flatMap((g) => g.items.map((i) => assocKey(g.recordId, i)));
  const n = shownKeys.filter((k) => checked.has(k)).length;
  const allCollapsed = shown.length > 0 && shown.every((g) => collapsed.has(g.recordId));
  const setMany = (keys: string[], on: boolean) =>
    setChecked((cur) => {
      const next = new Set(cur);
      for (const k of keys) {
        if (on) next.add(k);
        else next.delete(k);
      }
      return next;
    });
  return (
    <DesignModal
      id="modalReviewAssociations"
      title="Review Associations"
      large
      footerClass="crm-justify-content-end"
      onClose={onClose}
      footer={
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
      }
    >
      <p className="crm-text-muted crm-fs-7 crm-mb-4">
        Association type controls which types appear in the list. Association labels refine results
        within a type. If you want a specific label for one type, use both filters together.
      </p>
      <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-flex-wrap crm-gap-3 crm-mb-4">
        <div className="crm-d-flex crm-align-items-center crm-gap-2">
          <span className="crm-text-muted crm-fs-7 crm-fw-semibold">Filter by:</span>
          <CustomSelect
            placeholder="All association types"
            searchable={false}
            value={type}
            options={[
              { value: 'all', label: 'All association types' },
              ...types.map((t) => ({ value: t.type, label: t.plural })),
            ]}
            onChange={setType}
          />
          <CustomSelect
            placeholder="All labels"
            searchable={false}
            value={label}
            options={assocLabelOptions(groups ?? [])}
            onChange={setLabel}
          />
        </div>
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          onClick={() =>
            setCollapsed(allCollapsed ? new Set() : new Set(shown.map((g) => g.recordId)))
          }
        >
          {allCollapsed ? 'Expand all rows' : 'Collapse all rows'}
        </button>
      </div>
      <div className="crm-d-flex crm-align-items-center crm-gap-2 crm-p-2 crm-border-bottom crm-text-muted crm-fs-7 crm-mb-3">
        <input
          type="checkbox"
          className="lp-cb"
          aria-label="Select all associations"
          checked={shownKeys.length > 0 && n === shownKeys.length}
          onChange={(e) => setMany(shownKeys, e.target.checked)}
        />
        <span>{assocCountText(n)}</span>
        {n > 0 ? (
          <button
            type="button"
            className="btn-crm btn-crm--ghost btn-crm--sm crm-ms-auto"
            disabled={busy}
            onClick={() => onDissociate(shownKeys.filter((k) => checked.has(k)))}
          >
            <LpIcon name="link" className="iconSize-14" /> Dissociate
          </button>
        ) : null}
      </div>
      {loadError ? <Alert tone="danger">{loadError}</Alert> : null}
      {!groups && !loadError ? (
        <p className="crm-text-muted crm-m-0">Loading associations…</p>
      ) : null}
      <div className="di-assoc-tree">
        {shown.map((g) => {
          const keys = g.items.map((i) => assocKey(g.recordId, i));
          const isCollapsed = collapsed.has(g.recordId);
          return (
            <div
              key={g.recordId}
              className={cn(
                'di-assoc-group crm-border-bottom crm-py-2',
                isCollapsed && 'is-collapsed',
              )}
            >
              <div className="crm-d-flex crm-align-items-center crm-gap-2 crm-mb-2">
                <input
                  type="checkbox"
                  className="lp-cb"
                  aria-label={`Select ${g.name}'s associations`}
                  disabled={!keys.length}
                  checked={keys.length > 0 && keys.every((k) => checked.has(k))}
                  onChange={(e) => setMany(keys, e.target.checked)}
                />
                <button
                  type="button"
                  className="di-assoc-toggle-btn"
                  aria-expanded={!isCollapsed}
                  onClick={() =>
                    setCollapsed((cur) => {
                      const next = new Set(cur);
                      if (next.has(g.recordId)) next.delete(g.recordId);
                      else next.add(g.recordId);
                      return next;
                    })
                  }
                >
                  <CrmIcon name="chevron-down" className="iconSize-14 di-assoc-arrow" />
                  <span className="crm-fw-bold">{g.name}</span>
                </button>
                <span className="crm-text-muted crm-fs-7">{associatedText(g.items.length)}</span>
              </div>
              {isCollapsed ? null : (
                <div className="di-assoc-subitems crm-ps-4">
                  {g.items.map((i) => {
                    const k = assocKey(g.recordId, i);
                    return (
                      <div
                        key={k}
                        className="crm-d-flex crm-align-items-center crm-justify-content-between crm-py-1"
                      >
                        <label className="crm-d-flex crm-align-items-center crm-gap-2 crm-m-0">
                          <input
                            type="checkbox"
                            className="lp-cb"
                            checked={checked.has(k)}
                            onChange={(e) => setMany([k], e.target.checked)}
                          />
                          <span>{i.name}</span>
                        </label>
                        {i.primary ? <span className="badge badge--mapped">Primary</span> : null}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </DesignModal>
  );
}

// ── Inline editors (js:1005-1190) ───────────────────────────────────────────────────────────

/** The text box that replaces a cell's value: Enter or blur saves, Escape cancels. */
export function InlineTextInput({
  label,
  value,
  onCommit,
  onCancel,
}: {
  label: string;
  value: string;
  onCommit: (typed: string) => void;
  onCancel: () => void;
}) {
  const done = useRef(false);
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    ref.current?.focus();
    ref.current?.select();
  }, []);
  const finish = (fn: () => void) => {
    if (done.current) return;
    done.current = true;
    fn();
  };
  return (
    <input
      ref={ref}
      type="text"
      className="lp-inline-input"
      aria-label={`Edit ${label}`}
      defaultValue={value}
      onKeyDown={(e) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          finish(() => onCommit(e.currentTarget.value));
        } else if (e.key === 'Escape') {
          e.preventDefault();
          e.stopPropagation();
          finish(onCancel);
        }
      }}
      onBlur={(e) => finish(() => onCommit(e.currentTarget.value))}
    />
  );
}

/** The dropdown under a select cell: search, the options as badges (js:1073-1161). */
export function InlineSelectPopover({
  options,
  value,
  pos,
  onPick,
  onClose,
}: {
  options: Array<{ value: string; label: string }>;
  value: string;
  pos: { top: number; left: number; minWidth: number };
  onPick: (value: string, label: string) => void;
  onClose: () => void;
}) {
  const [q, setQ] = useState('');
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    const id = requestAnimationFrame(() => ref.current?.focus());
    return () => cancelAnimationFrame(id);
  }, []);
  const term = q.trim().toLowerCase();
  const shown = options.filter((o) => !term || o.label.toLowerCase().includes(term));
  return (
    <div
      className="lp-inline-popover"
      role="listbox"
      data-inline-popover=""
      style={{ top: pos.top, left: pos.left, minWidth: pos.minWidth }}
    >
      <div className="lp-inline-popover__search">
        <input
          ref={ref}
          type="search"
          className="lp-inline-popover__input"
          placeholder="Search"
          autoComplete="off"
          spellCheck={false}
          aria-label="Search options"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault();
              const first = shown[0];
              if (first) onPick(first.value, first.label);
            } else if (e.key === 'Escape') {
              e.preventDefault();
              e.stopPropagation();
              onClose();
            }
          }}
        />
        <span className="lp-inline-popover__search-icon" aria-hidden="true">
          <svg
            className="iconSize-14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <circle cx="11" cy="11" r="7" />
            <path d="m21 21-4.3-4.3" />
          </svg>
        </span>
      </div>
      <div className="lp-inline-popover__list">
        {shown.map((o) => {
          const on = o.value === value;
          return (
            <div
              key={o.value}
              className={cn('lp-inline-opt', on && 'is-selected')}
              data-val={o.value}
              role="option"
              aria-selected={on}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => onPick(o.value, o.label)}
            >
              <span className="badge">{o.label}</span>
              {on ? (
                <svg
                  className="lp-inline-opt__check iconSize-14"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              ) : null}
            </div>
          );
        })}
        {shown.length === 0 ? (
          <div className="lp-inline-popover__empty">No matching options</div>
        ) : null}
      </div>
    </div>
  );
}

// ── The controls: bar, dialogs, panels ─────────────────────────────────────────────────────

const ASSOC_MAX = 50;

type Dialog = 'assign' | 'share' | 'edit' | 'delete' | 'assoc';

/**
 * The bar and everything it opens, for the checked rows of the records tab. `onDone` reloads the
 * page once a call has finished (the tab count too).
 */
export function ImportBulkControls({
  objectType,
  singular,
  plural,
  ids,
  records,
  rights,
  meId,
  owners,
  ownersError,
  editProperties,
  linkTypes,
  naming,
  onClear,
  onDone,
}: {
  objectType: ImportObjectType;
  /** "Contact" */
  singular: string;
  /** "contacts" */
  plural: string;
  ids: string[];
  /** The checked rows, for the panels and Review Associations. */
  records: BxRecord[];
  rights: { delete: boolean; share: boolean };
  meId: string;
  /** Active members as "Name (email)"; null while loading. */
  owners: CustomSelectOption[] | null;
  ownersError: string | null;
  editProperties: EditField[] | null;
  linkTypes: Array<{ type: string; singular: string; plural: string }>;
  /** IDB4c: a new segment is named as the import's list. */
  naming: SegmentNaming;
  onClear: () => void;
  onDone: () => void;
}) {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const [moreOpen, setMoreOpen] = useState(false);
  const [dialog, setDialog] = useState<Dialog | null>(null);
  const [panel, setPanel] = useState<BulkPanel | null>(null);
  const [segmentOpen, setSegmentOpen] = useState(false);
  const [request, setRequest] = useState<{ dialog: BulkRequest; seq: number } | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [assoc, setAssoc] = useState<AssocGroup[] | null>(null);
  const [assocError, setAssocError] = useState<string | null>(null);
  const running = useRef(false);
  const alive = useRef(true);
  useEffect(() => {
    alive.current = true;
    return () => {
      alive.current = false;
    };
  }, []);

  // More closes on a click outside and on Escape (as the page's other dropdowns, js:892-911).
  useEffect(() => {
    if (!moreOpen) return;
    const onDown = (e: MouseEvent) => {
      if (!(e.target as Element).closest?.('.lp-bulk [data-dropdown]')) setMoreOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setMoreOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [moreOpen]);

  const builtIn = objectType === 'contact' || objectType === 'company' || objectType === 'deal';
  const count = ids.length;

  const openDialog = (d: Dialog) => {
    setError(null);
    setDialog(d);
  };
  const close = () => {
    if (!busy) setDialog(null);
  };

  /** Follows a started job to its end, then says what it did and reloads the page. */
  const follow = async (first: BulkOperation, done: BulkDone) => {
    // Stops when the tab goes, or after the job can't be read a few times in a row (`followBulk`).
    const end = await followBulk(first, () => alive.current);
    running.current = false;
    if (end.kind === 'stopped') return;
    if (end.kind === 'lost') {
      toast(`Couldn't follow the bulk action: ${end.error}`, 'danger');
      onDone();
      return;
    }
    const t = bulkResultToast(done, outcomeOfOperation(end.op), plural);
    toast(t.text, t.tone);
    onDone();
  };

  /**
   * Runs a dialog's call; a start that fails keeps the dialog open with the reason. False when
   * it didn't start (IDB7: the subscriptions panel stays open).
   */
  const run = async (call: BulkCall, done: BulkDone): Promise<boolean> => {
    if (running.current) {
      setError('Wait for the bulk action that is running to finish');
      return false;
    }
    setBusy(true);
    setError(null);
    try {
      if (call.kind === 'objects') {
        const res = await bulkObjectRecords(call.key, call.body);
        setDialog(null);
        const t = bulkResultToast(done, outcomeOfObjects(res), plural);
        toast(t.text, t.tone);
        onDone();
      } else {
        const op = await startBulk(call.objectType, call.body);
        running.current = true;
        setDialog(null);
        void follow(op, done);
      }
      return true;
    } catch (err) {
      setError(errorText(err));
      return false;
    } finally {
      setBusy(false);
    }
  };

  const loadAssoc = async () => {
    setAssoc(null);
    setAssocError(null);
    try {
      const groups = await Promise.all(
        records.slice(0, ASSOC_MAX).map(async (rec) => {
          const pages = await Promise.all(
            linkTypes.map((t) =>
              listLinkedRecords({
                fromType: objectType,
                fromId: rec.id,
                toType: t.type,
                limit: 50,
              }),
            ),
          );
          return {
            recordId: rec.id,
            name: rec.name,
            items: pages.flatMap((p, i) =>
              p.data.map((l) => ({
                type: linkTypes[i]!.type,
                id: l.id,
                name: l.name ?? 'Untitled',
                primary: l.isPrimary,
                labels: l.labels.map((x) => x.name),
              })),
            ),
          };
        }),
      );
      if (alive.current) setAssoc(groups);
    } catch (err) {
      if (alive.current) setAssocError(errorText(err));
    }
  };

  const dissociate = async (keys: string[]) => {
    const ok = await confirm({
      title: 'Remove associations',
      message: `Remove ${keys.length.toLocaleString('en-US')} ${keys.length === 1 ? 'association' : 'associations'}? The records stay; only the links between them are removed.`,
      confirmLabel: 'Remove',
      danger: true,
    });
    if (!ok) return;
    setBusy(true);
    const results = await Promise.allSettled(
      keys.map((k) => {
        const [fromId, toType, toId] = k.split('|');
        return unlinkRecords({
          fromType: objectType,
          fromId: fromId!,
          toType: toType!,
          toId: toId!,
        });
      }),
    );
    setBusy(false);
    const failed = results.filter((r) => r.status === 'rejected').length;
    const removed = results.length - failed;
    // Master's words (`DesignBulkPanels.tsx:1136-1139`): the design's Dissociate has none.
    toast(
      `${removed} ${removed === 1 ? 'association' : 'associations'} removed${failed ? `, ${failed} failed` : ''}`,
      failed ? 'info' : 'success',
    );
    void loadAssoc();
  };

  const onAct = (item: BulkItem) => {
    setMoreOpen(false);
    if (!item.works) {
      toast(`${item.label} is coming soon`, 'info');
      return;
    }
    switch (item.act) {
      case 'assign':
      case 'share':
      case 'edit':
      case 'delete':
        openDialog(item.act);
        return;
      case 'review-associations':
        openDialog('assoc');
        void loadAssoc();
        return;
      case 'create-tasks':
        setPanel('tasks');
        return;
      case 'create-leads':
        setPanel('leads');
        return;
      case 'enroll-sequence':
        setRequest((cur) => ({ dialog: 'sequence', seq: (cur?.seq ?? 0) + 1 }));
        return;
      case 'enroll-workflow':
        setRequest((cur) => ({ dialog: 'workflow', seq: (cur?.seq ?? 0) + 1 }));
        return;
      case 'add-segment':
        // IDB4c: the design's segment dialog for the checked rows (js:518).
        setSegmentOpen(true);
        return;
      case 'edit-subscriptions':
        // IDB7: the Contacts list's panel (contacts only, `bulkBar`).
        setError(null);
        setPanel('subs');
        return;
      default:
        toast(`${item.label} is coming soon`, 'info');
    }
  };

  return (
    <>
      {count > 0 ? (
        <ImportBulkBar
          objectType={objectType}
          plural={plural}
          count={count}
          rights={rights}
          moreOpen={moreOpen}
          onToggleMore={() => setMoreOpen((o) => !o)}
          onAct={onAct}
          onClear={onClear}
        />
      ) : null}
      <AssignDialog
        open={dialog === 'assign'}
        count={count}
        singular={singular}
        owners={owners}
        loadError={ownersError}
        error={error}
        busy={busy}
        onClose={close}
        onAssign={(ownerId, name) =>
          void run(assignCall(objectType, ids, ownerId), { kind: 'assign', owner: name })
        }
      />
      {objectType === 'contact' || objectType === 'company' ? (
        <ShareDialog
          open={dialog === 'share'}
          count={count}
          plural={plural}
          error={error}
          busy={busy}
          onClose={close}
          onShare={(input) =>
            void run(shareCall(objectType as BulkObject, ids, input), { kind: 'share' })
          }
        />
      ) : null}
      <EditDialog
        open={dialog === 'edit'}
        count={count}
        properties={editProperties}
        error={error}
        busy={busy}
        onClose={close}
        onUpdate={(field, raw) => {
          const bad = editValueError(field, raw);
          if (bad) {
            setError(bad);
            return;
          }
          const built = bulkEditValues(field, raw);
          if ('error' in built) {
            setError(built.error);
            return;
          }
          void run(editCall(objectType, ids, built.values), {
            kind: 'edit',
            property: field.label,
          });
        }}
      />
      <DeleteDialog
        open={dialog === 'delete'}
        count={count}
        error={error}
        busy={busy}
        onClose={close}
        onDelete={() => void run(deleteCall(objectType, ids), { kind: 'delete' })}
      />
      <ReviewAssociationsDialog
        open={dialog === 'assoc'}
        groups={assoc}
        loadError={assocError}
        types={linkTypes}
        busy={busy}
        onClose={close}
        onDissociate={(keys) => void dissociate(keys)}
      />
      {builtIn ? (
        <>
          <DesignBulkPanels
            panel={panel}
            onClose={() => setPanel(null)}
            objectType={objectType}
            singular={singular.toLowerCase()}
            plural={plural}
            count={count}
            loadRecords={async () => records}
            owners={(owners ?? []).map((o) => ({ value: o.value, label: o.label }))}
            teams={[]}
            meId={meId}
            linkTypes={linkTypes}
            coverageProps={[]}
            onDone={onDone}
            onSubscriptions={
              objectType === 'contact'
                ? (input) => run(subscriptionsCall(ids, input), { kind: 'subscriptions' })
                : undefined
            }
            subscriptionsError={panel === 'subs' ? error : null}
          />
          {/* Master's Enroll in sequence / workflow dialogs (the segment page's way). */}
          <BulkActionsBar
            design
            headless
            request={request}
            objectType={objectType as BulkObject}
            noun={count === 1 ? singular.toLowerCase() : plural}
            count={count}
            selection={{ ids }}
            ownerOptions={[]}
            fields={[]}
            customDefs={[]}
            canDelete={false}
            onDone={onDone}
          />
        </>
      ) : null}
      <ImportSegmentDialog
        open={segmentOpen}
        count={count}
        noun={plural}
        objectType={objectType}
        source={{ kind: 'ids', ids }}
        naming={naming}
        onClose={() => setSegmentOpen(false)}
      />
      {confirmDialog}
    </>
  );
}
