'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { listCompanies } from '@/features/companies/api.client';
import type { CompanyListItem } from '@/features/companies/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { markTargetAccounts } from '../api.client';

const isTarget = (c: CompanyListItem) => {
  const v = c.customProperties?.hs_is_target_account;
  return v === true || v === 'true';
};

/**
 * HUB-711 "Choose target accounts": search companies, tick the ones to mark, and save. Companies
 * already marked show as such and can't be ticked again.
 */
export function ChooseTargetAccountsDialog({
  open,
  onClose,
  onSaved,
}: {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  const [q, setQ] = useState('');
  const [rows, setRows] = useState<CompanyListItem[] | null>(null);
  const [picked, setPicked] = useState<Map<string, string>>(new Map());
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const request = useRef(0);

  useEffect(() => {
    if (!open) return;
    const id = ++request.current;
    const t = window.setTimeout(() => {
      listCompanies({ search: q.trim() || undefined, searchMode: 'contains', limit: 25 }).then(
        (res) => id === request.current && setRows(res.data),
        (err: unknown) => id === request.current && setError(errorText(err)),
      );
    }, 250);
    return () => window.clearTimeout(t);
  }, [q, open]);

  useEffect(() => {
    if (open) return;
    setQ('');
    setRows(null);
    setPicked(new Map());
    setError(null);
    setBusy(false);
  }, [open]);

  const toggle = (c: CompanyListItem) =>
    setPicked((prev) => {
      const next = new Map(prev);
      if (next.has(c.id)) next.delete(c.id);
      else next.set(c.id, c.name);
      return next;
    });

  const save = async () => {
    if (!picked.size || busy) return;
    setBusy(true);
    setError(null);
    try {
      const res = await markTargetAccounts([...picked.keys()], true);
      if (res.failed.length) {
        setError(
          `${res.failed.length} could not be marked: ${res.failed
            .map((f) => `${picked.get(f.id) ?? f.id} (${f.message})`)
            .join('; ')}`,
        );
      }
      if (res.updated) {
        toast(`${res.updated} target account${res.updated === 1 ? '' : 's'} added`);
        onSaved();
      }
      if (!res.failed.length) onClose();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="taChoose" open={open} onClose={onClose} size="wide">
      <ModalHeader id="taChoose" title="Choose target accounts" onClose={onClose} />
      <div className="modal__body">
        <input
          type="search"
          className="input"
          placeholder="Search companies by name or domain"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <ul className="ta-pick">
          {rows === null ? (
            <li className="ta-muted">Loading companies…</li>
          ) : !rows.length ? (
            <li className="ta-muted">No companies match.</li>
          ) : (
            rows.map((c) => {
              const already = isTarget(c);
              return (
                <li key={c.id}>
                  <label className={cn('ta-pick__row', already && 'is-disabled')}>
                    <input
                      type="checkbox"
                      disabled={already}
                      checked={already || picked.has(c.id)}
                      onChange={() => toggle(c)}
                    />
                    <span className="ta-pick__name">{c.name}</span>
                    <span className="ta-muted">
                      {already ? 'Already a target account' : (c.domain ?? '')}
                    </span>
                  </label>
                </li>
              );
            })
          )}
        </ul>
        {error ? (
          <p className="ta-error" role="alert">
            {error}
          </p>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          disabled={!picked.size || busy}
          onClick={() => void save()}
        >
          {picked.size ? `Mark ${picked.size} as target accounts` : 'Mark as target accounts'}
        </button>
      </div>
    </CrmModal>
  );
}
