'use client';

import { useEffect, useMemo, useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  campaignChanges,
  linkTaskToCampaign,
  listCampaigns,
  unlinkTaskFromCampaign,
  type CampaignSummary,
  type CommentOn,
} from '../comments';

/**
 * TK3b (Tasks parity #674): Actions › Add to campaigns on the task page. The design's menu item
 * (activity.php:209) only shows a fixed toast (activity.js:189), so the picker is ours: every
 * campaign with a checkbox, the task's current ones ticked; Save links and unlinks. Linking is
 * admin only, as every campaign asset (campaigns API).
 */
export function TaskCampaignsDialog({
  open,
  taskId,
  assetType = 'task',
  onClose,
}: {
  open: boolean;
  taskId: string;
  /** CL10: a call (the call page's Actions › Add to campaigns), else a task. */
  assetType?: CommentOn;
  onClose: () => void;
}) {
  const toast = useToast();
  const [all, setAll] = useState<CampaignSummary[] | null>(null);
  const [before, setBefore] = useState<Set<string>>(new Set());
  const [picked, setPicked] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);
  const [q, setQ] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    setAll(null);
    setError(null);
    setQ('');
    Promise.all([listCampaigns(), listCampaigns(taskId, assetType)]).then(
      ([campaigns, linked]) => {
        if (!alive) return;
        const ids = new Set(linked.map((c) => c.id));
        setAll(campaigns);
        setBefore(ids);
        setPicked(new Set(ids));
      },
      (err: unknown) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [open, taskId, assetType]);

  const shown = useMemo(() => {
    const s = q.trim().toLowerCase();
    return (all ?? []).filter((c) => !s || c.name.toLowerCase().includes(s));
  }, [all, q]);

  const save = async () => {
    const { add, remove } = campaignChanges(before, picked);
    if (!add.length && !remove.length) return onClose();
    setBusy(true);
    try {
      // One at a time, so a refusal names what was saved before it.
      for (const id of add) await linkTaskToCampaign(id, taskId, assetType);
      for (const id of remove) await unlinkTaskFromCampaign(id, taskId, assetType);
      toast(
        add.length && !remove.length
          ? `Added to ${add.length} campaign${add.length === 1 ? '' : 's'}`
          : 'Campaigns updated',
      );
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
      // Show what is saved now.
      listCampaigns(taskId, assetType).then(
        (linked) => {
          const ids = new Set(linked.map((c) => c.id));
          setBefore(ids);
          setPicked(new Set(ids));
        },
        () => {},
      );
    } finally {
      setBusy(false);
    }
  };

  const close = busy ? () => {} : onClose;
  return (
    <CrmModal id="taskCampaigns" open={open} onClose={close}>
      <ModalHeader id="taskCampaigns" title="Add to campaigns" onClose={close} />
      <div className="modal__body">
        {error ? (
          <p role="alert">Campaigns couldn&rsquo;t load: {error}</p>
        ) : all === null ? (
          <p className="crm-text-muted">Loading campaigns…</p>
        ) : all.length === 0 ? (
          <p className="crm-text-muted">There are no campaigns yet.</p>
        ) : (
          <>
            <input
              className="input crm-mb-3"
              type="search"
              placeholder="Search campaigns"
              aria-label="Search campaigns"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
            <ul className="crm-list-unstyled" style={{ maxHeight: 320, overflowY: 'auto' }}>
              {shown.map((c) => (
                <li key={c.id} className="crm-py-1">
                  <label className="check">
                    <input
                      type="checkbox"
                      checked={picked.has(c.id)}
                      onChange={() =>
                        setPicked((cur) => {
                          const next = new Set(cur);
                          if (next.has(c.id)) next.delete(c.id);
                          else next.add(c.id);
                          return next;
                        })
                      }
                    />
                    <span className="check__box" aria-hidden />
                    <span>{c.name}</span>
                  </label>
                </li>
              ))}
              {shown.length === 0 ? <li className="crm-text-muted">No campaigns found</li> : null}
            </ul>
          </>
        )}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={close} disabled={busy}>
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          disabled={busy || all === null || error !== null}
          onClick={() => void save()}
        >
          Save
        </button>
      </div>
    </CrmModal>
  );
}
