import { graphql, unmaskFragment } from "@/gql";
import { type FeaturedBlockFragment } from "@/gql/graphql";
import Link from "next/link";
import { Image } from "@/components/general/Image";
import { RichText } from "@/components/general/RichText";
import { ImageFragmentDefinition } from "@/lib/common";
import { internalHref } from "@/lib/links";
import styles from "./featuredBlock.module.scss";

const FeaturedBlockFragmentDefinition = graphql(`
  fragment FeaturedBlock on FeaturedBlock {
    title
    featuredBlockText: text
    linkText
    imagePosition
    backgroundColor
    featuredPage {
      contentType
      pageType
      url
      ... on EventPage {
        featuredImage {
          ...Image
        }
      }
      ... on NewsPage {
        featuredImage {
          ...Image
        }
      }
    }
    featuredImageOverride {
      ...Image
    }
  }
`);

export const FeaturedBlock = ({
  block,
}: {
  block: FeaturedBlockFragment;
}) => {
  const image = unmaskFragment(
    ImageFragmentDefinition,
    block.featuredImageOverride
  );
  // TODO: fetch image from target page

  const pageUrl = block.featuredPage.url;
  const featuredHref = pageUrl ? internalHref(pageUrl) ?? pageUrl : "#";

  return (
    <div
      className={styles.featuredBlock}
      data-background-color={block.backgroundColor ?? ""}
    >
      <div className={styles.text}>
        <h2>{block.title}</h2>
        <div>
          <RichText content={block.featuredBlockText} />
        </div>
        <Link href={featuredHref}>
          {block.linkText} &rarr;
        </Link>
      </div>
      {image && (
        <div className={styles.image}>
          <Image
            src={image.url}
            alt={image.alt ?? ""}
            width={image.width}
            height={image.height}
            sizes="(max-width: 800px) 100vw, 50vw"
          />
        </div>
      )}
      {!image && <div className={styles.placeholderImage} />}
    </div>
  );
};
