import {
  MaterialIcon,
  type MaterialIconSetIconProps,
} from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { serverClient } from "@/lib/trpc/server"

import Link from "@/components/TempDesignSystem/Link"
import Body from "@/components/TempDesignSystem/Text/Body"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import { getValueFromContactConfig } from "@/utils/contactConfig"

import styles from "./contactRow.module.css"

import type { ContactRowProps } from "@/types/components/sidebar/joinLoyaltyContact"

export default async function ContactRow({ contact }: ContactRowProps) {
  const caller = await serverClient()
  const data = await caller.contentstack.base.contact()
  if (!data) {
    return null
  }

  const val = getValueFromContactConfig(contact.contact_field, data)
  const footnote = contact.footnote
    ? getValueFromContactConfig(contact.footnote, data)
    : null

  if (!val) {
    return null
  }

  let Icon = null
  if (contact.contact_field.includes("email")) {
    Icon = MailIcon
  } else if (contact.contact_field.includes("phone")) {
    Icon = PhoneIcon
  }

  let openableLink = val
  if (contact.contact_field.includes("email")) {
    openableLink = `mailto:${val}`
  } else if (contact.contact_field.includes("phone")) {
    openableLink = `tel:${val}`
  }

  return (
    <div className={styles.wrapper}>
      <Body color="burgundy" textTransform="bold">
        {contact.display_text}
      </Body>
      <Link
        className={styles.link}
        href={openableLink}
        textDecoration="underline"
        size="small"
      >
        {Icon ? <Icon size={20} color="Icon/Interactive/Default" /> : null}
        {val}
      </Link>
      {footnote && <Footnote color="burgundy">{footnote}</Footnote>}
    </div>
  )
}

function PhoneIcon(props: MaterialIconSetIconProps) {
  return <MaterialIcon icon="phone" {...props} />
}
function MailIcon(props: MaterialIconSetIconProps) {
  return <MaterialIcon icon="mail" {...props} />
}
