import type { CompanyDuplicateMatches } from '@/features/companies/types';

type Match = CompanyDuplicateMatches['matches'][number];

function CompanyLink({ match }: { match: Match }) {
  return (
    <>
      <a href={`/companies/${match.id}`} target="_blank" rel="noopener">
        {match.name}
        <span className="crm-visually-hidden"> (opens in a new tab)</span>
      </a>
      {match.owner?.name ? ` (owner: ${match.owner.name})` : null}
    </>
  );
}

const others = (n: number, also: boolean) =>
  also
    ? `${n} more ${n === 1 ? 'company' : 'companies'} you don't have access to also ${n === 1 ? 'uses' : 'use'} it.`
    : n === 1
      ? "A company you don't have access to already uses this domain."
      : `${n} companies you don't have access to already use this domain.`;

/**
 * B3, point 33 (HubSpot's "Gosh, that looks familiar"; the design has no duplicate check): the
 * companies that already use the typed domain, under the domain field. It only advises: Create
 * stays as it is, and the API refuses a used domain (409). Companies the person may not open are
 * counted, never named. Links open in a new tab so the draft stays. The drawer puts it in a live
 * region that is always there, so it is announced when it appears.
 */
export function DuplicateDomainNotice({ matches, hidden }: { matches: Match[]; hidden: number }) {
  if (!matches.length && !hidden) return null;
  return (
    <div className="cc-dup">
      <p className="cc-dup__title">Gosh, that looks familiar.</p>
      {matches.length === 1 ? (
        <p className="cc-dup__text">
          <CompanyLink match={matches[0]!} /> already uses this domain.
        </p>
      ) : matches.length > 1 ? (
        <>
          <p className="cc-dup__text">These companies already use this domain:</p>
          <ul className="cc-dup__list">
            {matches.map((m) => (
              <li key={m.id}>
                <CompanyLink match={m} />
              </li>
            ))}
          </ul>
        </>
      ) : null}
      {hidden ? <p className="cc-dup__text">{others(hidden, matches.length > 0)}</p> : null}
    </div>
  );
}
