"use client"

import { useState } from "react"
import { useIntl } from "react-intl"

import { TeaserCardSidepeekContent } from "../../../types/sidepeekContent"
import { Button } from "../../Button"
import ButtonLink from "../../ButtonLink"
import { MaterialIcon } from "../../Icons/MaterialIcon"
import { JsonToHtml } from "../../JsonToHtml/JsonToHtml"
import SidePeek from "../../SidePeek"
import styles from "./sidepeek.module.css"

interface TeaserCardSidepeekProps {
  button: {
    call_to_action_text: string
  }
  sidePeekContent: TeaserCardSidepeekContent
}

export default function TeaserCardSidepeek({
  button,
  sidePeekContent,
}: TeaserCardSidepeekProps) {
  const intl = useIntl()
  const [sidePeekIsOpen, setSidePeekIsOpen] = useState(false)
  const { heading, content, primary_button, secondary_button } = sidePeekContent

  return (
    <div className={styles.teaserCardSidepeek}>
      <Button
        onPress={() => setSidePeekIsOpen(true)}
        variant="Secondary"
        color="Primary"
        size="sm"
      >
        {button.call_to_action_text}
        <MaterialIcon icon="chevron_right" size={20} color="CurrentColor" />
      </Button>
      <SidePeek
        title={heading}
        isOpen={sidePeekIsOpen}
        handleClose={() => setSidePeekIsOpen(false)}
        openInRoot
        closeLabel={intl.formatMessage({
          id: "common.close",
          defaultMessage: "Close",
        })}
      >
        {content ? (
          <JsonToHtml
            nodes={content.json.children}
            embeds={content.embedded_itemsConnection.edges}
          />
        ) : null}
        <div className={styles.ctaContainer}>
          {primary_button && (
            <ButtonLink
              variant="Primary"
              color="Primary"
              size="sm"
              href={primary_button.href}
              target={primary_button.openInNewTab ? "_blank" : undefined}
            >
              {primary_button.title}
            </ButtonLink>
          )}
          {secondary_button && (
            <ButtonLink
              variant="Secondary"
              color="Primary"
              size="sm"
              href={secondary_button.href}
              target={secondary_button.openInNewTab ? "_blank" : undefined}
            >
              {secondary_button.title}
            </ButtonLink>
          )}
        </div>
      </SidePeek>
    </div>
  )
}
