import { graphql, unmaskFragment } from "@/gql";
import { type ContactEntityBlockFragment } from "@/gql/graphql";
import styles from "./contactEntityBlock.module.scss";
import {
  ContactEntityFragmentDefinition,
  ImageFragmentDefinition,
  formatNorwegianPhoneNumber,
  formatPhoneE164,
} from "@/lib/common";
import { Icon } from "../general/Icon";
import { Image } from "../general/Image";

const ContactEntityBlockFragmentDefinition = graphql(`
  fragment ContactEntityBlock on ContactEntityBlock {
    contactEntity {
      ...ContactEntity
    }
  }
`);

export const ContactEntityBlock = ({
  block,
}: {
  block: ContactEntityBlockFragment;
}) => {
  const contact = unmaskFragment(
    ContactEntityFragmentDefinition,
    block?.contactEntity
  );
  const image = unmaskFragment(ImageFragmentDefinition, contact?.image);

  if (!contact) {
    return <></>;
  }

  const phoneE164 = contact.phoneNumber && formatPhoneE164(contact.phoneNumber);
  const phoneFormatted = phoneE164 && formatNorwegianPhoneNumber(phoneE164);

  return (
    <li className={styles.contactItem}>
      <div className={styles.image}>
        {!image && (
          <img
            src="/assets/graphics/portrait-pig.svg"
            className={styles.portraitPlaceholder}
          />
        )}
        {image && (
          <Image
            src={image.url}
            alt={image.alt ?? ""}
            width={image.width}
            height={image.height}
            sizes="25vw"
            className={styles.portrait}
          />
        )}
      </div>
      <div className={styles.text}>
        <h1 className={styles.name}>{contact.name}</h1>
        {contact.title && <p className={styles.role}>{contact.title}</p>}
        {(contact.email || phoneE164) && (
          <ul className={styles.contact}>
            {contact.email && (
              <li>
                <span className={styles.icon}>
                  <Icon type="email" />
                </span>
                <a href={`mailto:${contact.email}`} target="_blank">
                  {contact.email}
                </a>
              </li>
            )}
            {phoneE164 && (
              <li>
                <span className={styles.icon}>
                  <Icon type="phone" />
                </span>
                <a href={`tel:${phoneE164}`} target="_blank">
                  {phoneFormatted}
                </a>
              </li>
            )}
          </ul>
        )}
      </div>
    </li>
  );
};
