/**
 * TEAM: frontend_infra
 *
 * @flow strict
 */
/* eslint-disable react/forbid-elements */
import * as React from "react";

const KEYCODES = {
  abc: "2",
  def: "3",
  ghi: "4",
  jkl: "5",
  mno: "6",
  pqrs: "7",
  tuv: "8",
  wxyz: "9",
};

type PhoneNumberType = "sms" | "text" | "fax";

type Props = {|
  /** The phone number displayed */
  +phoneNumber?: string,
  /** The type of the PhoneNumber */
  +type?: PhoneNumberType,
|};

/**
 * @category Data display
 * @short Display and link a phone number
 * @brandStatus V3
 * @status Beta
 * The PhoneNumber component displays the phone number and provides a clickable link that calls the number directly.
 */
export default function PhoneNumber({
  phoneNumber,
  type,
}: Props): React.Element<"a"> {
  const url = formatPhoneNumber(phoneNumber || "", type);
  return <a href={url}>{phoneNumber}</a>;
}

// Converts letters to numbers and removes punctuation
function formatPhoneNumber(prettyNumber: string, type?: PhoneNumberType) {
  const number = Object.keys(KEYCODES).reduce(
    (number, letters) =>
      number.replace(new RegExp(`[${letters}]`, "gi"), KEYCODES[letters]),
    prettyNumber.replace(/(\s|\(|\)|-)/g, "")
  );

  let protocol = "tel";
  // eslint-disable-next-line default-case
  switch ((type || "").toLowerCase()) {
    case "sms":
    case "text":
      protocol = "sms";
      break;
    case "fax":
      protocol = "fax";
      break;
  }

  return `${protocol}:${number}`;
}
