import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import type { DuplicateMatch } from './contactEmailDuplicates';

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

/**
 * D07b (HubSpot's "Hold the phone!", the user's call, 10 Nov; the design has no card): the
 * contacts that already use the typed email, one card each (initials, the name linking to the
 * record in a new tab so the draft stays, the phone). Contacts the person may not open are
 * counted, never named, in Companies' words (`DuplicateDomainNotice`).
 */
export function DuplicateContactNotice({
  email,
  singular,
  matches,
  hidden,
}: {
  /** The email as looked up (trimmed, lower case). */
  email: string;
  /** The object's label, "Contact". */
  singular: string;
  matches: DuplicateMatch[];
  hidden: number;
}) {
  if (!matches.length && !hidden) return null;
  return (
    <div className="ccd-dup">
      <p className="ccd-dup__lead">
        Hold the phone! It looks like a {singular} with the email address <strong>{email}</strong>{' '}
        already exists.
      </p>
      {matches.map((m) => {
        const name = m.name || m.email || singular;
        return (
          <div className="ccd-dup__card" key={m.id}>
            <Avatar name={name} size="lg" />
            <div className="ccd-dup__who">
              <a
                className="ccd-dup__name"
                href={`/contacts/${m.id}`}
                target="_blank"
                rel="noopener"
              >
                {name}
                <svg
                  className="icon iconSize-14"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  aria-hidden
                >
                  <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3" />
                </svg>
                <span className="crm-visually-hidden"> (opens in a new tab)</span>
              </a>
              {m.phone ? <p className="ccd-dup__phone">{m.phone}</p> : null}
            </div>
          </div>
        );
      })}
      {hidden ? <p className="ccd-dup__text">{others(hidden, matches.length > 0)}</p> : null}
    </div>
  );
}
