'use client';

// Deals parity audit #16 (HUB-629): creating a deal warns when deals with the same name exist
// (a warning only: the deal can still be created). Create deal (`CreateDealDrawer`) and, DL14, the
// contact and company pages' "Add deal > Create new" (`AddAssociationDesignDrawer`) use it.
import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { listDeals } from '@/features/deals/api.client';
import type { Deal } from '@/features/deals/types';

/** Wait this long after typing before looking for deals with the same name. */
const LOOKUP_MS = 400;

/** The same name, ignoring case and spaces around it. */
export function sameDealName(a: string, b: string): boolean {
  return a.trim().toLowerCase() === b.trim().toLowerCase();
}

/**
 * Deals named exactly `name` (3 characters or more), looked up a moment after typing stops while
 * `active`. A failed lookup shows nothing: the warning is a hint, not a check.
 */
export function useSameNameDeals(active: boolean, name: string): Deal[] {
  const [found, setFound] = useState<Deal[]>([]);
  useEffect(() => {
    const wanted = name.trim();
    setFound([]);
    if (!active || wanted.length < 3) return;
    const ctrl = new AbortController();
    const timer = window.setTimeout(() => {
      listDeals({ search: wanted, limit: 5 }, { signal: ctrl.signal }).then(
        (res) => setFound(res.data.filter((d) => sameDealName(d.name, wanted))),
        () => {},
      );
    }, LOOKUP_MS);
    return () => {
      window.clearTimeout(timer);
      ctrl.abort();
    };
  }, [active, name]);
  return found;
}

/** The warning under the name field: each deal links to its page (new tab). */
export function SameNameDealsWarning({ deals }: { deals: Deal[] }) {
  return (
    <div aria-live="polite">
      {deals.length ? (
        <Alert tone="warning">
          {deals.length === 1
            ? 'A deal with this name already exists: '
            : 'Deals with this name already exist: '}
          {deals.map((d, i) => (
            <span key={d.id}>
              {i ? ', ' : null}
              <a href={`/deals/${d.id}`} target="_blank" rel="noopener">
                {d.name}
                <span className="crm-visually-hidden"> (opens in a new tab)</span>
              </a>{' '}
              ({d.stage.name}
              {d.owner?.name ? `, ${d.owner.name}` : ''})
            </span>
          ))}
          . You can still create it, or open the existing deal instead.
        </Alert>
      ) : null}
    </div>
  );
}
