import styles from './styles.module.scss'
import { ContactPerson } from '@/payload-types'
import Image, { StaticImageData } from 'next/image'
import { SecureEmail } from '@/components/SecureEmail/SecureEmail'
import { extractEmailPartsEncoded } from '@/utils/dto/email'

type ContactPersonCardProps = {
  contact: null | string | undefined | ContactPerson
  photo?: StaticImageData
}

export const ContactPersonCard = ({
  contact,
  photo,
}: ContactPersonCardProps) => {
  if (
    contact === null ||
    contact === undefined ||
    typeof contact === 'string'
  ) {
    return null
  }

  let user, domain = null;
  if (contact.email) {
    let data = extractEmailPartsEncoded(contact.email)
    user = data.user;
    domain = data.domain;
  }

  return (
    <div className={styles.card}>
      <div>
        {photo ? (
          <Image
            className={styles.photo}
            src={photo}
            alt={contact.name}
            width={200}
            height={200}
            unoptimized={false}
          />
        ) : (
          <div className={styles.photoPlaceholder} />
        )}
      </div>

      <div>
        {contact.role && (
          <h3 className={styles.role}>{contact.role}</h3>
        )}
        <div className={styles.name}>{contact.name}</div>
        <div className={styles.phoneEmail}>
          {user && domain && (
            <span>✉️ <SecureEmail user={user} domain={domain} /></span>
          )}

          {contact.telephone && (
            <span>
              📞 <a href={`tel:${contact.telephone}`}>
              {contact.telephone}
            </a>
            </span>
          )}
        </div>

      </div>
    </div>
  )
}