'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { LpIcon } from '@/features/list-page/ui/LpIcon';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { LpPopover } from '@/features/list-page/ui/LpPopover';
import { LpSide } from '@/features/list-page/ui/LpSide';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import {
  createObjectRecord,
  listLinkedRecords,
  unlinkRecords,
} from '@/features/objects/api.client';
import { conflictRecordOf } from '@/features/objects/leads';
import { leadsResult } from '../leadsResult';
import {
  finishSubscriptions,
  subscriptionTypeOptions,
  type SubsPick,
  type SubscriptionsInput,
} from '../subscriptionsResult';
import { enrichCompanies } from '@/features/settings/ui/data-enrichment/api.client';
import { listSubscriptionTypes } from '@/features/subscriptions/api.client';
import { useObjectSchema } from '@/features/objects/useObjectSchema';
import { listTeamOptions } from '@/features/members/api.client';
import { listAllOwners } from '@/features/owners/api.client';
import { createTask } from '@/features/tasks/api.client';
import type { TaskPriority } from '@/features/tasks/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

/** A selected record as the panels need it. */
export interface BxRecord {
  id: string;
  name: string;
  href: string;
  /** Has the address (or domain) enrichment needs. */
  eligible: boolean;
  /** Enrichment coverage: whether each property has a value. */
  filled: Record<string, boolean>;
}

export type BulkPanel =
  | 'enrich'
  | 'smart'
  | 'coverage'
  | 'tasks'
  | 'leads'
  | 'assoc'
  | 'subs'
  | 'share'
  | 'intent'
  | 'agent';

const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/** The most records a panel works on one by one (tasks, leads, associations). */
const ONE_BY_ONE_MAX = 200;
/** Review Associations shows the links of this many records. */
const ASSOC_MAX = 50;

function Info({ text }: { text: string }) {
  return (
    <span className="lp-mm__info" tabIndex={0} role="img" aria-label={text} title={text}>
      <LpIcon name="info" />
    </span>
  );
}

/** "Due date" choices (list-page.js `dueOptions`) and their dates. */
function dueOptions(today = new Date()): Array<{ v: string; label: string; date: Date | null }> {
  const t = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const biz = (k: number) => {
    const d = new Date(t);
    while (k > 0) {
      d.setDate(d.getDate() + 1);
      if (d.getDay() % 6) k -= 1;
    }
    return d;
  };
  const add = (days: number, months = 0) => {
    const d = new Date(t);
    if (months) d.setMonth(d.getMonth() + months);
    else d.setDate(d.getDate() + days);
    return d;
  };
  const md = (d: Date) => `${MON[d.getMonth()]} ${d.getDate()}`;
  const b2 = biz(2);
  const b3 = biz(3);
  return [
    { v: 'today', label: 'Today', date: t },
    { v: 'tomorrow', label: 'Tomorrow', date: add(1) },
    { v: 'b2', label: `In 2 business days (${WEEKDAYS[b2.getDay()]})`, date: b2 },
    { v: 'b3', label: `In 3 business days (${WEEKDAYS[b3.getDay()]})`, date: b3 },
    { v: 'w1', label: `In 1 week (${md(add(7))})`, date: add(7) },
    { v: 'w2', label: `In 2 weeks (${md(add(14))})`, date: add(14) },
    { v: 'm1', label: `In 1 month (${md(add(0, 1))})`, date: add(0, 1) },
    { v: 'm3', label: `In 3 months (${md(add(0, 3))})`, date: add(0, 3) },
    { v: 'm6', label: `In 6 months (${md(add(0, 6))})`, date: add(0, 6) },
    { v: 'custom', label: 'Custom date', date: null },
  ];
}

/** Runs `fn` on each record (a few at a time); counts what worked. */
async function eachRecord<T>(
  items: T[],
  fn: (item: T) => Promise<void>,
): Promise<{ ok: number; failed: Array<{ item: T; error: unknown }> }> {
  let ok = 0;
  const failed: Array<{ item: T; error: unknown }> = [];
  for (let i = 0; i < items.length; i += 4) {
    await Promise.all(
      items.slice(i, i + 4).map((item) =>
        fn(item).then(
          () => {
            ok += 1;
          },
          (error: unknown) => failed.push({ item, error }),
        ),
      ),
    );
  }
  return { ok, failed };
}

/**
 * The 28 Oct design's bulk action panels (list-page.js `bxEnrich`, `bxSmart`, `bxCoverage`,
 * `bxTasks`, `bxLeads`, `bxAssoc`, `bxSubs`, `bulkShare`). Create tasks, Create leads and Review
 * Associations work on the CRM; enrichment coverage is counted on the selected records. Company
 * enrichment fills fields from the public record of each domain. Smart properties have no API yet.
 * Share and subscriptions (IDB7) run when the page passes their handler.
 */
export function DesignBulkPanels({
  panel,
  onClose,
  objectType,
  singular,
  plural,
  pluralName,
  count,
  loadRecords,
  owners,
  teams,
  meId,
  linkTypes,
  coverageProps,
  onDone,
  onShare,
  shareError,
  onSubscriptions,
  subscriptionsError,
}: {
  panel: BulkPanel | null;
  onClose: () => void;
  /** contact, company, deal, or a custom object's key (leads: Create tasks and leads aren't offered). */
  objectType: string;
  /** "contact" */
  singular: string;
  /** "contacts" (or "contact" for one record: the count's noun) */
  plural: string;
  /** "contacts", whatever the count. */
  pluralName?: string;
  count: number;
  /** The selected records (all matching ones when "Select all" is on, up to a limit). */
  loadRecords: () => Promise<BxRecord[]>;
  owners: CustomSelectOption[];
  teams: CustomSelectOption[];
  meId: string;
  /** Record types the selected records link to (Review Associations). */
  linkTypes: Array<{ type: string; singular: string; plural: string }>;
  /** Properties enrichment fills ("Job Title", ...), with the record field that holds each. */
  coverageProps: string[];
  onDone: () => void;
  /** S5: starts the Share job (contacts and companies); without it Share is "coming soon". */
  onShare?: (input: ShareInput) => Promise<boolean>;
  /** Why the last Share could not start. */
  shareError?: string | null;
  /**
   * IDB7: starts "Edit communication subscriptions" (contacts) with the business's real types;
   * without it the panel keeps its sample types and Finish is "coming soon".
   */
  onSubscriptions?: (input: SubscriptionsInput) => Promise<boolean>;
  /** Why the last subscriptions change could not start. */
  subscriptionsError?: string | null;
}) {
  const toast = useToast();
  /** The CRM object Create tasks and Create leads link to. */
  const crmType = objectType === 'company' || objectType === 'deal' ? objectType : 'contact';
  const [records, setRecords] = useState<BxRecord[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const noun = (n: number) => (n === 1 ? singular : plural);
  const nN = (n: number) => `${n.toLocaleString('en-US')} ${noun(n)}`;
  const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
  const soon = (what: string) => toast(`${what} is coming soon`, 'info');

  useEffect(() => {
    if (
      !panel ||
      panel === 'subs' ||
      panel === 'share' ||
      panel === 'enrich' ||
      panel === 'smart' ||
      panel === 'intent' ||
      panel === 'agent'
    ) {
      setRecords(null);
      return;
    }
    let alive = true;
    setRecords(null);
    setLoadError(null);
    loadRecords().then(
      (rs) => alive && setRecords(rs),
      (err: unknown) => alive && setLoadError(errorText(err)),
    );
    return () => {
      alive = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- loads once per opened panel
  }, [panel]);

  const loading = !records && !loadError ? <p className="lp-muted">Loading {plural}…</p> : null;
  const failed = loadError ? <p className="crm-text-danger">{loadError}</p> : null;
  /**
   * The panel works on fewer records than are selected: "Select all" loads up to 500, and a
   * panel acts on at most `max` (one request per record). Said before anything runs.
   */
  const capNote = (max: number) => {
    if (!records) return null;
    const used = Math.min(records.length, max);
    if (used >= count) return null;
    return (
      <p className="lp-bx__cap lp-muted" role="note">
        Only the first {used.toLocaleString('en-US')} of {nN(count)} are included. Filter the list
        to work on the rest.
      </p>
    );
  };

  return (
    <>
      <EnrichSide
        open={panel === 'enrich'}
        n={count}
        singular={singular}
        others={objectType === 'company' ? 'contacts' : 'companies'}
        other={objectType === 'company' ? 'contact' : 'company'}
        isContact={objectType === 'contact'}
        onClose={onClose}
        onGo={() => {
          if (objectType !== 'company') {
            soon('Data enrichment');
            return;
          }
          void (async () => {
            try {
              const selected = await loadRecords();
              const ids = selected
                .filter((record) => record.eligible)
                .map((record) => record.id)
                .slice(0, 50);
              if (!ids.length) {
                toast('These companies need a domain before they can be enriched.', 'info');
                return;
              }
              const result = await enrichCompanies(ids);
              onClose();
              onDone();
              toast(
                result.enriched
                  ? `Enriched ${result.enriched} ${result.enriched === 1 ? 'company' : 'companies'}${
                      result.properties.length ? `: ${result.properties.join(', ')}` : ''
                    }.`
                  : 'No public company data was found for these domains.',
                result.enriched ? 'success' : 'info',
              );
            } catch (err) {
              toast(errorText(err), 'danger');
            }
          })();
        }}
      />
      <LpSide
        open={panel === 'smart'}
        title="Fill smart property"
        onClose={onClose}
        className="lp-side--bx lp-side--smart"
        footer={
          <div className="lp-bx__stack">
            <span className="lp-bx__cred">
              <LpIcon name="coins" />
              <span>Current: 0%</span>
            </span>
            <div className="lp-bx__acts">
              <button type="button" className="lp-btn lp-btn--primary" disabled>
                <LpIcon name="sparkle" />
                Fill smart properties
              </button>
              <button type="button" className="lp-btn lp-btn--plain" onClick={onClose}>
                Cancel
              </button>
            </div>
          </div>
        }
      >
        <div className="lp-bx">
          <div className="lp-field">
            <label>Fill smart properties</label>
            <p className="lp-muted">
              No smart properties yet. Smart properties (filled by the Data Agent with web research)
              are coming soon.
            </p>
          </div>
          <fieldset className="lp-field lp-bx__fs">
            <legend>Fill options</legend>
            <div className="lp-radios">
              <label className="lp-radio">
                <input type="radio" name="lpSpMode" defaultChecked disabled />
                <span>Fill empty values only (0 values)</span>
              </label>
              <label className="lp-radio">
                <input type="radio" name="lpSpMode" disabled />
                <span>Fill empty values and overwrite existing values (0 values)</span>
              </label>
            </div>
          </fieldset>
          <div className="lp-bx__card">
            <span className="lp-bx__badge">Fill selection</span>
            <p>
              <strong>0 values to be filled on selection</strong>
            </p>
            <p>
              0 values across {count.toLocaleString('en-US')} records on the selection can be filled
              with 0 smart properties. If any record results in an error, you will not be charged a
              credit.
            </p>
          </div>
        </div>
      </LpSide>
      <LpSide
        open={panel === 'coverage'}
        title="Enrichment data test"
        onClose={onClose}
        className="lp-side--bx lp-side--wide"
        footer={
          <div className="lp-bx__acts">
            <button
              type="button"
              className="lp-btn lp-btn--primary"
              onClick={() => {
                onClose();
                soon('Data enrichment');
              }}
            >
              Enrich records
            </button>
            <button type="button" className="lp-btn lp-btn--plain" onClick={onClose}>
              Cancel
            </button>
          </div>
        }
      >
        <div className="lp-bx">
          {loading}
          {failed}
          {capNote(Number.POSITIVE_INFINITY)}
          {records ? (
            <CoverageBody
              records={records}
              props={coverageProps}
              noun={nN}
              Many={cap(plural)}
              basis={
                objectType === 'company'
                  ? 'domain'
                  : objectType === 'contact' || objectType === 'deal'
                    ? 'email'
                    : 'company'
              }
            />
          ) : null}
        </div>
      </LpSide>
      <TasksSide
        open={panel === 'tasks'}
        records={records}
        status={loading ?? failed ?? capNote(ONE_BY_ONE_MAX)}
        title={`Create tasks for ${nN(count)}`}
        singular={cap(singular)}
        owners={owners}
        meId={meId}
        objectType={crmType}
        onClose={onClose}
        onDone={(ok, bad) => {
          toast(
            `${ok.toLocaleString('en-US')} ${ok === 1 ? 'task' : 'tasks'} created${bad ? `, ${bad} failed` : ''}`,
            bad ? 'info' : 'success',
          );
          onClose();
          onDone();
        }}
      />
      {panel === 'leads' ? (
        <LeadsSide
          records={records}
          status={loading ?? failed ?? capNote(ONE_BY_ONE_MAX)}
          title={`Create Lead for ${nN(count)}`}
          objectType={crmType}
          onClose={onClose}
          onDone={(ok, existing, errors) => {
            toast(
              leadsResult(ok, existing, errors),
              errors.length ? 'danger' : existing ? 'info' : 'success',
              {
                durationMs: existing || errors.length ? 8000 : 4000,
              },
            );
            onClose();
            onDone();
          }}
        />
      ) : null}
      {panel === 'assoc' ? (
        <AssocModal
          records={records}
          status={loading ?? failed ?? capNote(ASSOC_MAX)}
          objectType={objectType}
          linkTypes={linkTypes}
          onClose={onClose}
          onChanged={onDone}
        />
      ) : null}
      <SubsSide
        open={panel === 'subs'}
        n={count}
        real={Boolean(onSubscriptions)}
        startError={subscriptionsError ?? null}
        onClose={onClose}
        onGo={(pick, typeIds) =>
          finishSubscriptions({ pick, typeIds }, onSubscriptions, { close: onClose, soon })
        }
      />
      <IntentModal
        open={panel === 'intent'}
        n={count}
        onClose={onClose}
        onGo={() => {
          onClose();
          soon('Tracking intent signals');
        }}
      />
      {panel === 'agent' ? (
        <AgentDialog
          plural={pluralName ?? plural}
          onClose={onClose}
          onSetup={() => soon('The prospecting agent')}
        />
      ) : null}
      {onShare ? (
        <DesignShareModal
          open={panel === 'share'}
          n={count}
          noun={noun}
          plural={pluralName ?? plural}
          error={shareError ?? null}
          onClose={onClose}
          onShare={onShare}
          onLearn={() => soon('Record sharing help')}
        />
      ) : (
        <ShareModal
          open={panel === 'share'}
          n={count}
          noun={noun}
          plural={plural}
          users={owners}
          teams={teams}
          onClose={onClose}
          onGo={() => {
            onClose();
            soon('Sharing records with users and teams');
          }}
        />
      )}
    </>
  );
}

function EnrichSide({
  open,
  n,
  singular,
  other,
  others,
  isContact,
  onClose,
  onGo,
}: {
  open: boolean;
  n: number;
  singular: string;
  other: string;
  others: string;
  isContact: boolean;
  onClose: () => void;
  onGo: () => void;
}) {
  const [assoc, setAssoc] = useState(false);
  return (
    <LpSide
      open={open}
      title={`Enrich ${singular} records?`}
      onClose={onClose}
      className="lp-side--bx"
      footer={
        <div className="lp-bx__acts">
          <button type="button" className="lp-btn lp-btn--primary" onClick={onGo}>
            Enrich records
          </button>
          <button type="button" className="lp-btn lp-btn--plain" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <div className="lp-bx">
        <p>
          You have selected <strong>{n.toLocaleString('en-US')}</strong>{' '}
          {n === 1 ? 'record' : 'records'} to enrich.
        </p>
        <div className="lp-bx__box">
          <h3>Enrich associated records</h3>
          <p>We will attempt to enrich available properties for all associated {others}.</p>
          <label className="lp-check">
            <input type="checkbox" checked={assoc} onChange={(e) => setAssoc(e.target.checked)} />
            <span>Enrich {other} records</span>
          </label>
        </div>
        <p>
          When you enrich these records, we will use the field mappings defined in your Data
          Enrichment settings.{' '}
          <a className="lp-bx__a" href="/settings/data-enrichment">
            Review your settings
          </a>
        </p>
        <p className="lp-muted">
          By using enrichment tools (Enrichment, Data Tests, and similar features), you confirm that
          you understand the “Enrichment Products” terms in your Agreement apply.
        </p>
        {isContact ? (
          <p className="lp-muted">
            If a contact isn’t found, data enrichment will proactively research and enrich the
            record if data becomes available. Newly enriched data may take time to appear.
          </p>
        ) : null}
      </div>
    </LpSide>
  );
}

/** "Enrichment data test": real counts on the selected records. */
function CoverageBody({
  records,
  props,
  noun,
  Many,
  basis,
}: {
  records: BxRecord[];
  props: string[];
  noun: (n: number) => string;
  Many: string;
  /** What enrichment finds a record by: "domain", "email", or (leads) "company". */
  basis: string;
}) {
  const n = records.length;
  const ok = records.filter((r) => r.eligible).length;
  const rate = n ? Math.round((ok / n) * 100) : 0;
  return (
    <>
      <p>
        The enrichment data test checks enrichment coverage of the selected records in your CRM.
      </p>
      <hr className="lp-bx__hr" />
      <p>
        <strong>{noun(n)}</strong> analyzed. <strong>{noun(ok)}</strong> with an eligible {basis}.
      </p>
      <div className="lp-bx__stat">
        <strong>{ok.toLocaleString('en-US')}</strong>
        <span>{Many} with available enrichment</span>
        <span>{rate}% match rate</span>
      </div>
      <div className="lp-bx__covh">
        <h3>Property coverage today</h3>
        <span className="lp-bx__tag">{Many}</span>
      </div>
      <div className="lp-bx__cov" tabIndex={0} aria-label="Coverage by property">
        {props.map((p) => {
          const pc = n ? Math.round((records.filter((r) => r.filled[p]).length / n) * 100) : 0;
          return (
            <div key={p} className="lp-bx__covr">
              <span>{p}</span>
              <strong>{pc}%</strong>
              <span className="lp-bx__bar" role="img" aria-label={`${pc}%`}>
                <span style={{ width: `${pc}%` }} />
              </span>
            </div>
          );
        })}
      </div>
      <p>
        When you enrich these records, we will use the field mappings defined in your Data
        Enrichment settings.{' '}
        <a className="lp-bx__a" href="/settings/data-enrichment">
          Review your settings
        </a>
      </p>
      <p className="lp-muted">
        By using enrichment tools (Enrichment, Data Tests, and similar features), you confirm that
        you understand the “Enrichment Products” terms in your Agreement apply.
      </p>
    </>
  );
}

function TasksSide({
  open,
  records,
  status,
  title,
  singular,
  owners,
  meId,
  objectType,
  onClose,
  onDone,
}: {
  open: boolean;
  records: BxRecord[] | null;
  status: React.ReactNode;
  title: string;
  singular: string;
  owners: CustomSelectOption[];
  meId: string;
  objectType: 'contact' | 'company' | 'deal';
  onClose: () => void;
  onDone: (ok: number, failed: number) => void;
}) {
  const toast = useToast();
  const due = useMemo(() => dueOptions(), []);
  const [custom, setCustom] = useState(false);
  const [titleText, setTitleText] = useState('');
  const [type, setType] = useState('todo');
  const [prio, setPrio] = useState('none');
  const [owner, setOwner] = useState(meId);
  const [queue, setQueue] = useState('none');
  const [dueV, setDueV] = useState('b3');
  const [dueDate, setDueDate] = useState('');
  const [time, setTime] = useState('08:00');
  const [rem, setRem] = useState('none');
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (!open) return;
    setCustom(false);
    setTitleText('');
    setType('todo');
    setPrio('none');
    setOwner(meId);
    setQueue('none');
    setDueV('b3');
    setDueDate('');
    setTime('08:00');
    setRem('none');
  }, [open, meId]);

  const go = async () => {
    if (custom && !titleText.trim()) {
      toast('Enter a task title', 'danger');
      return;
    }
    if (!records) return;
    const day =
      dueV === 'custom'
        ? dueDate
          ? new Date(`${dueDate}T00:00:00`)
          : null
        : due.find((d) => d.v === dueV)?.date;
    let dueAt: string | undefined;
    if (day) {
      const [h, m] = time.split(':').map(Number);
      const at = new Date(day);
      at.setHours(h || 0, m || 0, 0, 0);
      dueAt = at.toISOString();
    }
    setBusy(true);
    const list = records.slice(0, ONE_BY_ONE_MAX);
    const res = await eachRecord(list, (r) =>
      createTask({
        title: custom ? titleText.trim() : `Task for ${r.name}`,
        taskType: type,
        priority: prio === 'none' ? null : (prio as TaskPriority),
        ...(dueAt ? { dueAt } : {}),
        assigneeId: owner || undefined,
        links: [{ objectType, id: r.id }],
      }).then(() => undefined),
    );
    setBusy(false);
    if (rem !== 'none' || queue !== 'none')
      toast(
        'Reminders and task queues are coming soon; the tasks were created without them.',
        'info',
      );
    if (records.length > ONE_BY_ONE_MAX)
      toast(`Tasks were created for the first ${ONE_BY_ONE_MAX} records.`, 'info');
    onDone(res.ok, res.failed.length);
  };

  return (
    <LpSide
      open={open}
      title={title}
      onClose={onClose}
      className="lp-side--bx"
      footer={
        <div className="lp-bx__acts">
          <button
            type="button"
            className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
            disabled={!records || busy}
            onClick={() => void go()}
          >
            Create tasks
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <div className="lp-bx">
        {status}
        {custom ? (
          <div className="lp-field">
            <label htmlFor="lpTkT">Title</label>
            <input
              id="lpTkT"
              className="lp-input"
              placeholder="Enter your task"
              value={titleText}
              onChange={(e) => setTitleText(e.target.value)}
              autoFocus
            />
          </div>
        ) : (
          <div className="lp-bx__tfor">
            <span>Task for</span>
            <span className="lp-bx__token">{singular} Name</span>
          </div>
        )}
        <button type="button" className="lp-link lp-bx__tog" onClick={() => setCustom((v) => !v)}>
          {custom ? 'Use the default title instead' : 'Use a custom title instead'}
        </button>
        <div className="lp-bx__row">
          <div className="lp-field lp-bx__grow">
            <label>Task Type *</label>
            <CustomSelect
              className="lp-bx__select"
              placeholder="Select"
              value={type}
              searchable={false}
              options={[
                { value: 'call', label: 'Call' },
                { value: 'email', label: 'Email' },
                { value: 'todo', label: 'To-do' },
              ]}
              onChange={setType}
            />
          </div>
          <div className="lp-field lp-bx__prio">
            <label>Priority *</label>
            <CustomSelect
              className="lp-bx__select"
              placeholder="Select"
              value={prio}
              searchable={false}
              options={[
                { value: 'none', label: 'None' },
                { value: 'low', label: 'Low' },
                { value: 'medium', label: 'Medium' },
                { value: 'high', label: 'High' },
              ]}
              onChange={setPrio}
            />
          </div>
        </div>
        <div className="lp-field">
          <label>Assigned to</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder="Select"
            value={owner}
            options={owners}
            onChange={setOwner}
          />
        </div>
        <div className="lp-field">
          <label>Queue</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder="None"
            value={queue}
            searchable={false}
            options={[
              { value: 'none', label: 'None' },
              { value: 'follow', label: 'Follow-ups' },
              { value: 'calls', label: 'Call queue' },
            ]}
            onChange={setQueue}
          />
        </div>
        <div className="lp-field">
          <label>Due date</label>
          <div className="lp-bx__row">
            <div className="lp-bx__grow">
              <CustomSelect
                className="lp-bx__select"
                placeholder="Select"
                value={dueV}
                searchable={false}
                options={due.map((d) => ({ value: d.v, label: d.label }))}
                onChange={setDueV}
              />
            </div>
            <label className="lp-bx__time">
              <LpIcon name="clock" />
              <input
                type="time"
                className="lp-input"
                aria-label="Due time"
                value={time}
                onChange={(e) => setTime(e.target.value)}
              />
            </label>
          </div>
          {dueV === 'custom' ? (
            <input
              className="lp-input"
              type="date"
              aria-label="Custom due date"
              value={dueDate}
              onChange={(e) => setDueDate(e.target.value)}
            />
          ) : null}
        </div>
        <div className="lp-field">
          <label>Reminder</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder="No reminder"
            value={rem}
            searchable={false}
            options={[
              { value: 'none', label: 'No reminder' },
              { value: 'due', label: 'At task due time' },
              { value: '30m', label: '30 minutes before' },
              { value: '1h', label: '1 hour before' },
              { value: '1d', label: '1 day before' },
              { value: '1w', label: '1 week before' },
            ]}
            onChange={setRem}
          />
          <p className="lp-bx__help">
            You can customize your default settings.{' '}
            <a className="lp-bx__a" href="/settings">
              Go to settings
              <LpIcon name="external" className="lp-i--xs" />
            </a>
          </p>
        </div>
      </div>
    </LpSide>
  );
}

function LeadsSide({
  records,
  status,
  title,
  objectType,
  onClose,
  onDone,
}: {
  records: BxRecord[] | null;
  status: React.ReactNode;
  title: string;
  objectType: 'contact' | 'company' | 'deal';
  onClose: () => void;
  /** Created, refused because the record already has an open lead, and the other errors. */
  onDone: (ok: number, existing: number, errors: string[]) => void;
}) {
  const state = useObjectSchema('lead');
  const schema = state.status === 'ready' ? state.schema : null;
  const [pipe, setPipe] = useState('');
  const [stage, setStage] = useState('');
  const [type, setType] = useState('');
  const [label, setLabel] = useState('');
  const [busy, setBusy] = useState(false);
  const pipeline = schema?.pipelines.find((p) => p.id === pipe) ?? schema?.pipelines[0];
  const stages = (pipeline?.stages ?? []).filter((s) => !s.archived);
  const optsOf = (name: string) =>
    (schema?.defs.find((d) => d.name === name)?.options ?? [])
      .filter((o) => !o.archived)
      .map((o) => ({ value: o.value, label: o.label }));
  useEffect(() => {
    if (!schema) return;
    const p = schema.pipelines[0];
    setPipe(p?.id ?? '');
    setStage((p?.stages.find((s) => /^new$/i.test(s.name)) ?? p?.stages[0])?.id ?? '');
    setType(
      schema.defs
        .find((d) => d.name === 'hs_lead_type')
        ?.options?.find((o) => /new business/i.test(o.label))?.value ?? '',
    );
    setLabel('');
  }, [schema]);

  const go = async () => {
    if (!records || !schema) return;
    setBusy(true);
    const nameField = schema.definition.displayProperty;
    const res = await eachRecord(records.slice(0, ONE_BY_ONE_MAX), (r) =>
      createObjectRecord(schema.definition.key, {
        customProperties: {
          [nameField]: r.name,
          ...(type ? { hs_lead_type: type } : {}),
          ...(label ? { hs_lead_label: label } : {}),
        },
        ...(pipeline ? { pipelineId: pipeline.id, ...(stage ? { stageId: stage } : {}) } : {}),
        ...(objectType === 'company' ? { companyId: r.id } : { contactId: r.id }),
      }).then(() => undefined),
    );
    setBusy(false);
    // A record with an open lead is refused with a conflict (HUB-338): reported apart from
    // real failures, which keep their reason.
    const existing = res.failed.filter((f) => conflictRecordOf(f.error)).length;
    const errors = res.failed
      .filter((f) => !conflictRecordOf(f.error))
      .map((f) => errorText(f.error));
    onDone(res.ok, existing, errors);
  };

  return (
    <LpSide
      open
      title={title}
      onClose={onClose}
      className="lp-side--bx"
      footer={
        <div className="lp-bx__acts">
          <button
            type="button"
            className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
            disabled={!records || !schema || busy}
            onClick={() => void go()}
          >
            Create
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <div className="lp-bx">
        {status}
        {state.status === 'missing' ? (
          <p className="crm-text-danger">This CRM has no Leads object.</p>
        ) : null}
        <p className="lp-bx__right">
          <a
            className="lp-bx__a"
            href="/create-form-editor?object=lead"
            target="_blank"
            rel="noopener"
          >
            Edit this form
            <LpIcon name="external" className="lp-i--xs" />
          </a>
        </p>
        <div className="lp-field">
          <label>Lead Pipeline</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder="Select"
            value={pipeline?.id ?? ''}
            searchable={false}
            options={(schema?.pipelines ?? []).map((p) => ({ value: p.id, label: p.name }))}
            onChange={(v) => {
              setPipe(v);
              const p = schema?.pipelines.find((x) => x.id === v);
              setStage(p?.stages.find((s) => !s.archived)?.id ?? '');
            }}
          />
        </div>
        <div className="lp-field">
          <label>Lead stage</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder="Select"
            value={stage}
            options={stages.map((s) => ({ value: s.id, label: s.name }))}
            onChange={setStage}
          />
        </div>
        <div className="lp-field">
          <label>Lead Type</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder=" "
            value={type}
            searchable={false}
            options={[{ value: '', label: ' ' }, ...optsOf('hs_lead_type')]}
            onChange={setType}
          />
        </div>
        <div className="lp-field">
          <label>Lead Label</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder=" "
            value={label}
            searchable={false}
            options={[{ value: '', label: ' ' }, ...optsOf('hs_lead_label')]}
            onChange={setLabel}
          />
        </div>
      </div>
    </LpSide>
  );
}

export type AssocRow = {
  rec: BxRecord;
  groups: Array<{ type: string; items: Array<{ id: string; name: string; labels: string[] }> }>;
};

/**
 * CL5b: where Review Associations reads and removes links, for objects that don't link through
 * `/associations/records` (calls are activities). Without it, records' links as before.
 */
export type AssocSource = {
  load: (records: BxRecord[]) => Promise<AssocRow[]>;
  unlink: (fromId: string, toType: string, toId: string) => Promise<unknown>;
};

/** "Review Associations" (list-page.js `bxAssoc`): the selected records' links, by type and label. */
export function AssocModal({
  records,
  status,
  objectType,
  linkTypes,
  onClose,
  onChanged,
  source,
}: {
  records: BxRecord[] | null;
  status: React.ReactNode;
  objectType: string;
  linkTypes: Array<{ type: string; singular: string; plural: string }>;
  onClose: () => void;
  onChanged: () => void;
  source?: AssocSource;
}) {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const [rows, setRows] = useState<AssocRow[] | null>(null);
  const [types, setTypes] = useState<string[]>([]);
  const [labels, setLabels] = useState<string[]>([]);
  const [sel, setSel] = useState<Set<string>>(new Set());
  const [open, setOpen] = useState<Set<string>>(new Set());
  const [all, setAll] = useState(false);
  const [menu, setMenu] = useState<'type' | 'label' | null>(null);
  const [busy, setBusy] = useState(false);
  /** CL5b: why `source.load` failed (records' own loads show a type with no links instead). */
  const [loadError, setLoadError] = useState<string | null>(null);

  useEffect(() => {
    if (!records) return;
    let alive = true;
    const list = records.slice(0, ASSOC_MAX);
    if (source) {
      setLoadError(null);
      source.load(list).then(
        (r) => alive && setRows(r),
        (err) => alive && setLoadError(errorText(err)),
      );
      return () => {
        alive = false;
      };
    }
    void Promise.all(
      list.map(async (rec) => {
        const groups = await Promise.all(
          linkTypes.map(async (t) => {
            const page = await listLinkedRecords({
              fromType: objectType,
              fromId: rec.id,
              toType: t.type,
              limit: 50,
            }).catch(() => ({ data: [] }));
            return {
              type: t.type,
              items: page.data.map((l) => ({
                id: l.id,
                name: l.name ?? 'Untitled',
                labels: l.labels.map((x) => x.name),
              })),
            };
          }),
        );
        return { rec, groups };
      }),
    ).then((r) => alive && setRows(r));
    return () => {
      alive = false;
    };
  }, [records, linkTypes, objectType, source]);

  const tInfo = (t: string) => linkTypes.find((x) => x.type === t);
  const allLabels = useMemo(() => {
    const out = new Map<string, Set<string>>();
    for (const r of rows ?? [])
      for (const g of r.groups)
        for (const it of g.items)
          for (const l of it.labels) out.set(g.type, new Set([...(out.get(g.type) ?? []), l]));
    return out;
  }, [rows]);
  const shownGroups = (r: AssocRow) =>
    r.groups
      .filter((g) => !types.length || types.includes(g.type))
      .map((g) => ({
        ...g,
        items: g.items.filter(
          (it) => !labels.length || it.labels.some((l) => labels.includes(`${g.type}|${l}`)),
        ),
      }))
      .filter((g) => g.items.length);
  const keyOf = (r: AssocRow, type: string, id: string) => `${r.rec.id}|${type}|${id}`;
  const keysOf = (r: AssocRow, type?: string) =>
    shownGroups(r)
      .filter((g) => !type || g.type === type)
      .flatMap((g) => g.items.map((it) => keyOf(r, g.type, it.id)));
  const every = (rows ?? []).flatMap((r) => keysOf(r));
  const allOn = (ks: string[]) => ks.length > 0 && ks.every((k) => sel.has(k));
  const setKeys = (ks: string[], on: boolean) =>
    setSel((cur) => {
      const next = new Set(cur);
      for (const k of ks) {
        if (on) next.add(k);
        else next.delete(k);
      }
      return next;
    });
  const toggleOpen = (k: string) =>
    setOpen((cur) => {
      const next = new Set(cur);
      if (next.has(k)) next.delete(k);
      else next.add(k);
      return next;
    });
  const dissociate = async () => {
    const ks = [...sel];
    // Removing links can't be undone from here: ask first.
    const ok = await confirm({
      title: 'Remove associations',
      message: `Remove ${ks.length.toLocaleString('en-US')} ${ks.length === 1 ? 'association' : 'associations'}? The records stay; only the links between them are removed.`,
      confirmLabel: 'Remove',
      danger: true,
    });
    if (!ok) return;
    setBusy(true);
    const res = await eachRecord(ks, (k) => {
      const [fromId, toType, toId] = k.split('|');
      if (source) return source.unlink(fromId!, toType!, toId!).then(() => undefined);
      return unlinkRecords({ fromType: objectType, fromId: fromId!, toType: toType!, toId: toId! });
    });
    setBusy(false);
    setRows((cur) =>
      (cur ?? []).map((r) => ({
        ...r,
        groups: r.groups.map((g) => ({
          ...g,
          items: g.items.filter(
            (it) =>
              !ks.includes(keyOf(r, g.type, it.id)) ||
              res.failed.some((f) => f.item === keyOf(r, g.type, it.id)),
          ),
        })),
      })),
    );
    setSel(new Set());
    toast(
      `${res.ok} ${res.ok === 1 ? 'association' : 'associations'} removed${res.failed.length ? `, ${res.failed.length} failed` : ''}`,
      res.failed.length ? 'info' : 'success',
    );
    onChanged();
  };

  return (
    <LpModal
      open
      title="Review Associations"
      onClose={onClose}
      className="lp-modal--wide lp-modal--ra"
    >
      {confirmDialog}
      <p>
        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="lp-ra__bar">
        <span className="lp-ra__by">Filter by:</span>
        <span className="lp-ra__f">
          <button
            type="button"
            className="lp-chip__btn"
            aria-haspopup="true"
            aria-expanded={menu === 'type'}
            onClick={() => setMenu((m) => (m === 'type' ? null : 'type'))}
          >
            <span>Association type{types.length ? ` (${types.length})` : ''}</span>
            <LpIcon name="caret" />
          </button>
          {types.length ? (
            <button
              type="button"
              className="lp-ra__clr"
              aria-label="Clear association type filter"
              onClick={() => {
                setTypes([]);
                setLabels([]);
                setSel(new Set());
              }}
            >
              <LpIcon name="x" />
            </button>
          ) : null}
        </span>
        <span className="lp-ra__f">
          <button
            type="button"
            className="lp-chip__btn"
            aria-haspopup="true"
            aria-expanded={menu === 'label'}
            onClick={() => {
              const any = [...allLabels.entries()].some(
                ([t, ls]) => ls.size && (!types.length || types.includes(t)),
              );
              if (!any) {
                toast('You have no association labels for the selected association type.', 'info');
                return;
              }
              setMenu((m) => (m === 'label' ? null : 'label'));
            }}
          >
            <span>Association label{labels.length ? ` (${labels.length})` : ''}</span>
            <LpIcon name="caret" />
          </button>
          {labels.length ? (
            <button
              type="button"
              className="lp-ra__clr"
              aria-label="Clear association label filter"
              onClick={() => {
                setLabels([]);
                setSel(new Set());
              }}
            >
              <LpIcon name="x" />
            </button>
          ) : null}
        </span>
        <span className="lp-spacer" />
        <button
          type="button"
          className="lp-btn lp-btn--outline lp-btn--sm"
          onClick={() => {
            const next = !all;
            setAll(next);
            setOpen(
              next
                ? new Set(
                    (rows ?? []).flatMap((r) => [
                      r.rec.id,
                      ...shownGroups(r).map((g) => `${r.rec.id}|${g.type}`),
                    ]),
                  )
                : new Set(),
            );
          }}
        >
          {all ? 'Collapse all rows' : 'Expand all rows'}
        </button>
      </div>
      {menu === 'type' ? (
        <div className="lp-ra__types lp-ra__menu">
          {linkTypes.map((t) => (
            <label key={t.type} className="lp-check">
              <input
                type="checkbox"
                checked={types.includes(t.type)}
                onChange={(e) => {
                  const next = e.target.checked
                    ? [...types, t.type]
                    : types.filter((x) => x !== t.type);
                  setTypes(next);
                  setLabels((ls) =>
                    ls.filter((l) => !next.length || next.includes(l.split('|')[0]!)),
                  );
                  setSel(new Set());
                }}
              />
              <span>{t.plural}</span>
            </label>
          ))}
        </div>
      ) : null}
      {menu === 'label' ? (
        <div className="lp-ra__types lp-ra__menu">
          {[...allLabels.entries()]
            .filter(([t]) => !types.length || types.includes(t))
            .map(([t, ls]) => (
              <div key={t} className="lp-ra__lgrp">
                <strong className="lp-ra__lgh">{tInfo(t)?.plural ?? t}</strong>
                {[...ls].map((l) => {
                  const v = `${t}|${l}`;
                  return (
                    <label key={v} className="lp-check lp-ra__lopt">
                      <input
                        type="checkbox"
                        checked={labels.includes(v)}
                        onChange={(e) => {
                          setLabels((cur) =>
                            e.target.checked ? [...cur, v] : cur.filter((x) => x !== v),
                          );
                          setSel(new Set());
                        }}
                      />
                      <span>{l}</span>
                    </label>
                  );
                })}
              </div>
            ))}
        </div>
      ) : null}
      <div className="lp-ra">
        {status}
        {loadError ? <p className="crm-text-danger">{loadError}</p> : null}
        {records && !rows && !loadError ? <p className="lp-muted">Loading associations…</p> : null}
        {rows ? (
          <>
            <div className="lp-ra__head">
              <input
                type="checkbox"
                className="lp-cb"
                aria-label="Select all associations"
                checked={allOn(every)}
                disabled={!every.length}
                onChange={(e) => setKeys(every, e.target.checked)}
              />
              <span>
                {sel.size} {sel.size === 1 ? 'association' : 'associations'} selected on this page
              </span>
              {sel.size ? (
                <button
                  type="button"
                  className="lp-link"
                  disabled={busy}
                  onClick={() => void dissociate()}
                >
                  <LpIcon name="link" />
                  Dissociate
                </button>
              ) : null}
            </div>
            {rows.map((r) => {
              const gs = shownGroups(r);
              const total = gs.reduce((n, g) => n + g.items.length, 0);
              const ks = keysOf(r);
              const o = open.has(r.rec.id);
              return (
                <div key={r.rec.id} className="lp-ra__rec">
                  <div className="lp-ra__row">
                    <input
                      type="checkbox"
                      className="lp-cb"
                      aria-label={`Select ${r.rec.name} associations`}
                      checked={allOn(ks)}
                      disabled={!ks.length}
                      onChange={(e) => setKeys(ks, e.target.checked)}
                    />
                    <button
                      type="button"
                      className="lp-ra__tog"
                      aria-expanded={o}
                      aria-label={`Show associations of ${r.rec.name}`}
                      disabled={!total}
                      onClick={() => toggleOpen(r.rec.id)}
                    >
                      <LpIcon name={o ? 'caret' : 'right'} />
                    </button>
                    <div className="lp-ra__copy">
                      <a href={r.rec.href}>{r.rec.name}</a>
                      <small>
                        Associated to {total} {total === 1 ? 'record' : 'records'}
                      </small>
                    </div>
                  </div>
                  {o
                    ? gs.map((g) => {
                        const gid = `${r.rec.id}|${g.type}`;
                        const gk = keysOf(r, g.type);
                        const go = open.has(gid);
                        const info = tInfo(g.type);
                        return (
                          <div key={gid} className="lp-ra__grp">
                            <div className="lp-ra__row">
                              <input
                                type="checkbox"
                                className="lp-cb"
                                aria-label={`Select ${g.items.length} ${info?.plural ?? g.type}`}
                                checked={allOn(gk)}
                                onChange={(e) => setKeys(gk, e.target.checked)}
                              />
                              <button
                                type="button"
                                className="lp-ra__tog"
                                aria-expanded={go}
                                aria-label={`Show ${info?.plural ?? g.type}`}
                                onClick={() => toggleOpen(gid)}
                              >
                                <LpIcon name={go ? 'caret' : 'right'} />
                              </button>
                              <span>
                                {g.items.length}{' '}
                                {g.items.length === 1
                                  ? (info?.singular ?? g.type)
                                  : (info?.plural ?? g.type)}
                              </span>
                            </div>
                            {go
                              ? g.items.map((it) => {
                                  const k = keyOf(r, g.type, it.id);
                                  return (
                                    <div key={k} className="lp-ra__item">
                                      <input
                                        type="checkbox"
                                        className="lp-cb"
                                        aria-label={`Select ${it.name}`}
                                        checked={sel.has(k)}
                                        onChange={(e) => setKeys([k], e.target.checked)}
                                      />
                                      <Avatar name={it.name} size="sm" />
                                      <span className="lp-ra__nm">{it.name}</span>
                                      {it.labels.length ? (
                                        <span className="lp-ra__lb">{it.labels.join(', ')}</span>
                                      ) : null}
                                    </div>
                                  );
                                })
                              : null}
                          </div>
                        );
                      })
                    : null}
                </div>
              );
            })}
            {!rows.some((r) => shownGroups(r).length) ? (
              <p className="lp-ra__none">No associations match these filters.</p>
            ) : null}
          </>
        ) : null}
      </div>
    </LpModal>
  );
}

/** The design's sample types (list-page.js:3541-3544), kept where Finish is still "coming soon". */
const SAMPLE_SUBSCRIPTION_TYPES = [
  { value: 'marketing', label: 'Marketing Information' },
  {
    value: 'service',
    label:
      'Customer Service Communication - Receive feedback requests and customer service information',
  },
  { value: 'one', label: 'One to One - One to One emails' },
];

/**
 * The panel's types field (the design's `data-sub-types`, list-page.js:3528): the types, or
 * that they are loading or could not be loaded, then why the last Finish could not start.
 */
export function SubsTypesField({
  types,
  loadError,
  startError,
  picked,
  onToggle,
}: {
  /** Null while loading. */
  types: Array<{ value: string; label: string }> | null;
  loadError: string | null;
  startError: string | null;
  picked: string[];
  onToggle: (value: string, on: boolean) => void;
}) {
  return (
    <div className="lp-field">
      <label>
        Communication subscription types * <Info text="The email types this status applies to." />
      </label>
      {loadError ? (
        <p className="crm-text-danger">{loadError}</p>
      ) : !types ? (
        <p className="lp-muted">Loading subscription types…</p>
      ) : (
        types.map(({ value, label }) => (
          <label key={value} className="lp-check">
            <input
              type="checkbox"
              checked={picked.includes(value)}
              onChange={(e) => onToggle(value, e.target.checked)}
            />
            <span>{label}</span>
          </label>
        ))
      )}
      {startError ? <p className="crm-text-danger">{startError}</p> : null}
    </div>
  );
}

function SubsSide({
  open,
  n,
  real,
  startError,
  onClose,
  onGo,
}: {
  open: boolean;
  n: number;
  /** IDB7: the page runs Finish, so the business's own types are listed. */
  real: boolean;
  startError: string | null;
  onClose: () => void;
  onGo: (pick: SubsPick, typeIds: string[]) => Promise<void>;
}) {
  const [status, setStatus] = useState<SubsPick | ''>('');
  const [subs, setSubs] = useState<string[]>([]);
  const [types, setTypes] = useState<Array<{ value: string; label: string }> | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (!open) return;
    setStatus('');
    setSubs([]);
    // `busy` stays as it is: a start still in flight when the panel was closed and reopened
    // must not be sent twice (Finish clears it when the start ends).
    if (!real) {
      setTypes(SAMPLE_SUBSCRIPTION_TYPES);
      return;
    }
    let alive = true;
    setTypes(null);
    setLoadError(null);
    listSubscriptionTypes(false).then(
      (all) => alive && setTypes(subscriptionTypeOptions(all)),
      (err: unknown) => alive && setLoadError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [open, real]);
  return (
    <LpSide
      open={open}
      title="Edit subscription status for email"
      onClose={onClose}
      className="lp-side--bx lp-side--wide"
      footer={
        <div className="lp-bx__acts lp-bx__acts--end">
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            disabled={!(status && subs.length) || busy}
            onClick={async () => {
              if (!status) return;
              setBusy(true);
              try {
                await onGo(status, subs);
              } finally {
                setBusy(false);
              }
            }}
          >
            Finish
          </button>
        </div>
      }
    >
      <div className="lp-bx">
        <h3 className="lp-bx__h">What subscription status are you updating?</h3>
        <p>
          You’ve selected <strong>{n.toLocaleString('en-US')} contacts</strong> to update.
          Subscriptions will be edited for the primary email address for the contact. This will not
          change unsubscribes the recipient has explicitly requested.
        </p>
        <div className="lp-bx__rcards" role="radiogroup" aria-label="Subscription status">
          {[
            ['sub', 'Subscribe'],
            ['not', 'Not opted'],
            ['unsub', 'Unsubscribe'],
          ].map(([v, l]) => (
            <label key={v} className={cn('lp-bx__rcard', status === v && 'is-on')}>
              <input
                type="radio"
                name="lpSubS"
                value={v}
                checked={status === v}
                onChange={() => setStatus(v as SubsPick)}
              />
              <span>{l}</span>
            </label>
          ))}
        </div>
        {status ? (
          <SubsTypesField
            types={types}
            loadError={loadError}
            startError={startError}
            picked={subs}
            onToggle={(v, on) => setSubs((cur) => (on ? [...cur, v] : cur.filter((x) => x !== v)))}
          />
        ) : null}
      </div>
    </LpSide>
  );
}

/** What Share sends for every picked record (S5). */
export interface ShareInput {
  userIds: string[];
  teamIds: string[];
  userMode: 'append' | 'replace';
  teamMode: 'append' | 'replace';
}

export type PickOption = { value: string; label: string };

/**
 * The design's checkbox picker with a search box (list-page.js `multiPick`): the trigger reads
 * "No user", the one picked, or "N users".
 */
export function MultiPick({
  id,
  label,
  options,
  failed,
  picked,
  onChange,
  none,
  many,
}: {
  id: string;
  label: string;
  /** Null while loading. */
  options: PickOption[] | null;
  /** What to say when the options could not load. */
  failed: string | null;
  picked: string[];
  onChange: (next: string[]) => void;
  none: string;
  many: string;
}) {
  const ref = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const names = new Map((options ?? []).map((o) => [o.value, o.label]));
  const text = !picked.length
    ? none
    : picked.length === 1
      ? (names.get(picked[0]!) ?? '1 selected')
      : `${picked.length} ${many}`;
  const shown = (options ?? []).filter((o) =>
    o.label.toLowerCase().includes(q.trim().toLowerCase()),
  );
  return (
    <>
      <button
        ref={ref}
        type="button"
        className="ps-trigger"
        id={id}
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => {
          setQ('');
          setOpen((v) => !v);
        }}
      >
        <span className={cn('ps-trigger__val', !picked.length && 'is-placeholder')}>{text}</span>
        <svg
          className="ps-i ps-i--caret"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </button>
      <LpPopover
        pop="panel"
        arrow={false}
        open={open}
        anchorRef={ref}
        onClose={() => setOpen(false)}
        label={label}
        className="lp-pop--ms"
        width={ref.current?.offsetWidth}
        focus="input[type=search]"
      >
        <div className="lp-ms">
          <label className="lp-ms__search">
            <input
              type="search"
              className="lp-input"
              placeholder="Search"
              aria-label="Search"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
            <LpIcon name="search" />
          </label>
          <div className="lp-ms__list" role="group" aria-label={label}>
            {failed ? (
              <p className="lp-field__err" role="alert">
                {failed}
              </p>
            ) : options === null ? (
              <p className="lp-muted lp-ms__none">Loading…</p>
            ) : (
              <>
                {shown.map((o) => (
                  <label key={o.value} className="lp-check lp-ms__opt">
                    <input
                      type="checkbox"
                      value={o.value}
                      checked={picked.includes(o.value)}
                      onChange={(e) =>
                        onChange(
                          e.target.checked
                            ? [...picked, o.value]
                            : picked.filter((v) => v !== o.value),
                        )
                      }
                    />
                    <span>{o.label}</span>
                  </label>
                ))}
                {shown.length ? null : <p className="lp-muted lp-ms__none">No results</p>}
              </>
            )}
          </div>
        </div>
      </LpPopover>
    </>
  );
}

/**
 * Share N records (list-page.js `bulkShare`, S5): shared users and teams, each added to or
 * replacing what the records have. People are active members and teams the business's, loaded
 * when it opens. Update starts the bulk job; a start that fails keeps the dialog and says why.
 * Contacts and Companies; other lists keep `ShareModal`, which says sharing is coming soon.
 */
function DesignShareModal({
  open,
  n,
  noun,
  plural,
  error,
  onClose,
  onShare,
  onLearn,
}: {
  open: boolean;
  n: number;
  noun: (n: number) => string;
  plural: string;
  /** Why the last start failed. */
  error: string | null;
  onClose: () => void;
  /** Starts the job; false when it could not start. */
  onShare: (input: ShareInput) => Promise<boolean>;
  onLearn: () => void;
}) {
  const [u, setU] = useState<string[]>([]);
  const [t, setT] = useState<string[]>([]);
  const [um, setUm] = useState<ShareInput['userMode']>('append');
  const [tm, setTm] = useState<ShareInput['teamMode']>('append');
  const [busy, setBusy] = useState(false);
  const [people, setPeople] = useState<PickOption[] | null>(null);
  const [teams, setTeams] = useState<PickOption[] | null>(null);
  const [peopleFailed, setPeopleFailed] = useState(false);
  const [teamsFailed, setTeamsFailed] = useState(false);
  useEffect(() => {
    if (!open) return;
    setU([]);
    setT([]);
    setUm('append');
    setTm('append');
    setPeople(null);
    setTeams(null);
    setPeopleFailed(false);
    setTeamsFailed(false);
    let live = true;
    listAllOwners(false).then(
      (all) => {
        if (!live) return;
        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) setTeams(res.data.map((x) => ({ value: x.id, label: x.name })));
      },
      () => {
        if (live) setTeamsFailed(true);
      },
    );
    return () => {
      live = false;
    };
  }, [open]);
  const can = u.length > 0 || t.length > 0 || um === 'replace' || tm === 'replace';
  const radios = (
    name: string,
    what: string,
    mode: string,
    setMode: (v: 'append' | 'replace') => void,
  ) => (
    <div className="lp-radios lp-share__radios" role="radiogroup" aria-label={capFirst(what)}>
      {(['append', 'replace'] as const).map((m) => (
        <label key={m} className="lp-radio">
          <input
            type="radio"
            name={name}
            value={m}
            checked={mode === m}
            onChange={() => setMode(m)}
          />
          <span>
            {m === 'append' ? 'Append to current' : 'Replace current'} {what}
          </span>
        </label>
      ))}
    </div>
  );
  return (
    <LpModal
      open={open}
      title={`Share ${n.toLocaleString('en-US')} ${noun(n)}`}
      onClose={onClose}
      className="lp-modal--share"
      footer={
        <div className="lp-modal__acts">
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            disabled={!can || busy}
            onClick={async () => {
              setBusy(true);
              const ok = await onShare({ userIds: u, teamIds: t, userMode: um, teamMode: tm });
              setBusy(false);
              if (ok) onClose();
            }}
          >
            Update
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <p>
        Let users and teams access these {noun(n)} based on their permissions.
        <br />
        <a
          className="lp-link lp-share__learn"
          href="#"
          onClick={(e) => {
            e.preventDefault();
            onLearn();
          }}
        >
          Learn more about record sharing
          <LpIcon name="external" className="lp-i--xs" />
        </a>
      </p>
      <div className="lp-field">
        <label htmlFor="lpShU">
          Shared users{' '}
          <Info text={`Users who can access these ${plural} in addition to the owner.`} />
        </label>
        <MultiPick
          id="lpShU"
          label="Shared users"
          options={people}
          failed={peopleFailed ? "Couldn't load users" : null}
          picked={u}
          onChange={setU}
          none="No user"
          many="users"
        />
        {radios('lpShUm', 'shared users', um, setUm)}
      </div>
      <div className="lp-field">
        <label htmlFor="lpShT">
          Shared teams <Info text={`Teams whose members can access these ${plural}.`} />
        </label>
        <MultiPick
          id="lpShT"
          label="Shared teams"
          options={teams}
          failed={teamsFailed ? "Couldn't load teams" : null}
          picked={t}
          onChange={setT}
          none="No shared teams"
          many="teams"
        />
        {radios('lpShTm', 'shared teams', tm, setTm)}
      </div>
      {error ? (
        <p className="lp-field__err" role="alert">
          {error}
        </p>
      ) : null}
    </LpModal>
  );
}

const capFirst = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

function ShareModal({
  open,
  n,
  noun,
  plural,
  users,
  teams,
  onClose,
  onGo,
}: {
  open: boolean;
  n: number;
  noun: (n: number) => string;
  plural: string;
  users: CustomSelectOption[];
  teams: CustomSelectOption[];
  onClose: () => void;
  onGo: () => void;
}) {
  const [u, setU] = useState<string[]>([]);
  const [t, setT] = useState<string[]>([]);
  const [um, setUm] = useState('append');
  const [tm, setTm] = useState('append');
  useEffect(() => {
    if (open) {
      setU([]);
      setT([]);
      setUm('append');
      setTm('append');
    }
  }, [open]);
  const can = u.length > 0 || t.length > 0 || um === 'replace' || tm === 'replace';
  const pick = (
    label: string,
    tip: string,
    opts: CustomSelectOption[],
    vals: string[],
    setVals: (v: string[]) => void,
    mode: string,
    setMode: (v: string) => void,
    what: string,
    none: string,
  ) => (
    <div className="lp-field">
      <label>
        {label} <Info text={tip} />
      </label>
      <CustomSelect
        className="lp-bx__select"
        placeholder={vals.length ? `${vals.length} selected` : none}
        value=""
        options={opts.map((o) => ({
          value: o.value,
          label: `${vals.includes(o.value) ? '✓ ' : ''}${o.label}`,
        }))}
        onChange={(v) => setVals(vals.includes(v) ? vals.filter((x) => x !== v) : [...vals, v])}
      />
      <div className="lp-radios lp-share__radios" role="radiogroup" aria-label={what}>
        <label className="lp-radio">
          <input type="radio" checked={mode === 'append'} onChange={() => setMode('append')} />
          <span>Append to current {what}</span>
        </label>
        <label className="lp-radio">
          <input type="radio" checked={mode === 'replace'} onChange={() => setMode('replace')} />
          <span>Replace current {what}</span>
        </label>
      </div>
    </div>
  );
  return (
    <LpModal
      open={open}
      title={`Share ${n.toLocaleString('en-US')} ${noun(n)}`}
      onClose={onClose}
      className="lp-modal--share"
      footer={
        <div className="lp-modal__acts lp-modal__acts--start">
          <button type="button" className="lp-btn lp-btn--primary" disabled={!can} onClick={onGo}>
            Update
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <p>Let users and teams access these {noun(n)} based on their permissions.</p>
      {pick(
        'Shared users',
        `Users who can access these ${plural} in addition to the owner.`,
        users,
        u,
        setU,
        um,
        setUm,
        'shared users',
        'No user',
      )}
      {pick(
        'Shared teams',
        `Teams whose members can access these ${plural}.`,
        teams,
        t,
        setT,
        tm,
        setTm,
        'shared teams',
        'No shared teams',
      )}
    </LpModal>
  );
}

/**
 * Track intent signals (companies, list-page.js `bxIntent`): the signals to track and the
 * credit estimate (10 credits a company a month for the standard signals). Tracking has no API
 * yet, so Start tracking says so.
 */
function IntentModal({
  open,
  n,
  onClose,
  onGo,
}: {
  open: boolean;
  n: number;
  onClose: () => void;
  onGo: () => void;
}) {
  const [std, setStd] = useState(true);
  useEffect(() => {
    if (open) setStd(true);
  }, [open]);
  const what = n === 1 ? 'company' : 'companies';
  return (
    <LpModal
      open={open}
      title="Start tracking intent signals?"
      onClose={onClose}
      className="lp-modal--intent"
      footer={
        <div className="lp-modal__acts lp-modal__acts--start">
          <button type="button" className="lp-btn lp-btn--primary" disabled={!std} onClick={onGo}>
            Start tracking
          </button>
          <button type="button" className="lp-btn lp-btn--plain" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <p>
        You’ve selected <strong>{n.toLocaleString('en-US')}</strong> {what} to track intent signals
        on.
      </p>
      <p>
        <strong>Choose the signals you want to track:</strong>
      </p>
      <label className={cn('lp-bx__ocard', std ? 'is-on' : 'is-off')}>
        <input type="checkbox" checked={std} onChange={(e) => setStd(e.target.checked)} />
        <span>
          <strong>Standard signals</strong>
          <span>45+ signals like new hire, product launch, geo expansion and more.</span>
        </span>
      </label>
      <div className="lp-bx__ocard is-off">
        <input type="checkbox" disabled aria-label="Custom signal" />
        <span>
          <strong>Custom signal</strong>
          <span>Define custom signals that matter to your business.</span>
          <span className="lp-muted">Custom signals are coming soon.</span>
        </span>
      </div>
      <p>
        Credit estimate: <strong>{(std ? n * 10 : 0).toLocaleString('en-US')} credits/month</strong>
      </p>
      {std ? (
        <ul className="lp-bx__ul">
          <li>
            Standard signals: <strong>10 credits/company</strong> * {n.toLocaleString('en-US')}{' '}
            {what}
          </li>
        </ul>
      ) : null}
      <span className="lp-bx__cred">
        <LpIcon name="coins" />
        <span>Predicted: 0%</span>
      </span>
    </LpModal>
  );
}

/**
 * Enroll to agent (companies, list-page.js `bxAgent`): the prospecting agent has to be set up
 * first. The CRM has no prospecting agent yet, so setting it up says so.
 */
function AgentDialog({
  plural,
  onClose,
  onSetup,
}: {
  plural: string;
  onClose: () => void;
  onSetup: () => void;
}) {
  const setupRef = useRef<HTMLButtonElement>(null);
  const closeRef = useRef(onClose);
  closeRef.current = onClose;
  useEffect(() => {
    const opener = document.activeElement as HTMLElement | null;
    document.documentElement.classList.add('lp-lock');
    setupRef.current?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      e.stopPropagation();
      closeRef.current();
    };
    document.addEventListener('keydown', onKey, true);
    return () => {
      document.removeEventListener('keydown', onKey, true);
      document.documentElement.classList.remove('lp-lock');
      opener?.focus?.({ preventScroll: true });
    };
  }, []);
  if (typeof document === 'undefined') return null;
  return createPortal(
    <div className="lp-agent" role="dialog" aria-modal="true" aria-labelledby="lpAgT">
      <div className="lp-agent__in">
        <svg className="lp-agent__art" viewBox="0 0 160 150" aria-hidden="true">
          <ellipse cx="80" cy="128" rx="58" ry="16" fill="#fde7c8" />
          <path
            d="M30 112h100l-14 14H44z"
            fill="#f08a4b"
            stroke="#33475b"
            strokeWidth="5"
            strokeLinejoin="round"
          />
          <path
            d="M66 20h28l22 92H44z"
            fill="#f08a4b"
            stroke="#33475b"
            strokeWidth="5"
            strokeLinejoin="round"
          />
          <path d="M60 45h40l6 24H54zM50 88h60l4 16H46z" fill="#fff" />
          <ellipse cx="80" cy="20" rx="14" ry="6" fill="#f08a4b" stroke="#33475b" strokeWidth="5" />
        </svg>
        <h2 id="lpAgT">The prospecting agent has not been configured</h2>
        <p>To enroll {plural}, you need to set up the prospecting agent first.</p>
        <div className="lp-agent__acts">
          <button ref={setupRef} type="button" className="lp-btn lp-btn--primary" onClick={onSetup}>
            Set up the prospecting agent
            <LpIcon name="external" className="lp-i--xs" />
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </div>,
    document.body,
  );
}
