'use client';

import { useEffect, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import type { AssociationCandidate } from '@/features/associations/types';
import { RecordMultiPicker } from '@/features/deals/ui/actions/RecordMultiPicker';
import { addListMembers } from '@/features/lists/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { ADD_CONTACTS_MAX, addContactPick, addContactsCountText } from '../segment';
import { SegModal } from './primitives';

/**
 * S-04 (SG-3): a static segment's Actions › Add contacts, as HubSpot's dialog: pick up to 25
 * contacts, then add them (one POST /lists/:id/members call; the API takes up to 100).
 */
export function AddContactsModal({
  open,
  listId,
  onClose,
  onAdded,
}: {
  open: boolean;
  listId: string;
  onClose: () => void;
  /** Contacts joined the segment: reload its members, size and activity. */
  onAdded: () => void;
}) {
  const toast = useToast();
  const [picked, setPicked] = useState<AssociationCandidate[]>([]);
  const [busy, setBusy] = useState(false);

  // Starts empty each time it opens.
  useEffect(() => {
    if (open) setPicked([]);
  }, [open]);

  const full = picked.length >= ADD_CONTACTS_MAX;
  const add = async () => {
    if (busy || picked.length === 0) return;
    setBusy(true);
    try {
      const res = await addListMembers(
        listId,
        picked.map((p) => p.id),
      );
      toast(
        res.changed === 1
          ? '1 contact added to this segment.'
          : `${res.changed} contacts added to this segment.`,
        'success',
      );
      onAdded();
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <SegModal
      open={open}
      onClose={onClose}
      labelledBy="vcsAddContactsTitle"
      id="vcsAddContactsModal"
    >
      <header className="lp-modal__head">
        <h2 id="vcsAddContactsTitle">Add contacts</h2>
        <button type="button" className="lp-icon-btn" aria-label="Close" onClick={onClose}>
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="lp-modal__body">
        <label className="crm-fw-semibold crm-d-block" htmlFor="vcsAddContactsSearch">
          Choose contacts to add to this segment:
        </label>
        <div className="crm-d-flex crm-justify-content-between crm-fs-8 crm-mb-2">
          <span>You can add up to 25 contacts at a time.</span>
          <span id="vcsAddContactsCount">{addContactsCountText(picked.length)}</span>
        </div>
        <RecordMultiPicker
          id="vcsAddContactsSearch"
          type="contact"
          value={picked}
          // The picker adds one record at a time (or removes one); a 26th is refused.
          onChange={(next) => {
            const added = next.find((r) => !picked.some((p) => p.id === r.id));
            if (!added) return setPicked(next);
            if (full) toast('You can add up to 25 contacts at a time.', 'info');
            setPicked(addContactPick(picked, added));
          }}
          disabled={busy}
          placeholder="Choose contacts"
          linkedLabel="Selected"
        />
      </div>
      <footer className="lp-modal__foot">
        <div className="lp-modal__acts">
          <button
            type="button"
            className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
            id="vcsAddContactsBtn"
            disabled={busy || picked.length === 0}
            onClick={() => void add()}
          >
            Add contacts
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </footer>
    </SegModal>
  );
}
