/* eslint-disable @next/next/no-img-element */
import { ImageResponse } from "next/og";
import sharp from "sharp";

import { getOpportunityById } from "@/services/opportunities";
import PFRDefaultLogo from "@/components/common/sprites/pfr-default-logo-sprite";

export const size = {
  width: 1200,
  height: 630,
};

export const contentType = "image/png";

// OG images are not compatible with WebP.
async function convertWebpToPng(base64Webp: string): Promise<string> {
  const webpData = base64Webp.replace(/^data:image\/webp;base64,/, "");
  const webpBuffer = Buffer.from(webpData, "base64");
  const pngBuffer = await sharp(webpBuffer).png().toBuffer();
  return `data:image/png;base64,${pngBuffer.toString("base64")}`;
}

export default async function Image({ params }: { params: { id: number } }) {
  const id = params.id;
  const opportunity = await getOpportunityById(Number(id));

  if (!opportunity) {
    return new ImageResponse(
      <div tw="flex w-full h-full items-center justify-center bg-white">
        <p style={{ fontFamily: '"Inter"' }} tw="text-3xl text-gray-400">
          Opportunity not found
        </p>
      </div>,
      { ...size },
    );
  }

  const { thumbnail, title } = opportunity;

  const base64Thumbnail = thumbnail
    ? await convertWebpToPng(`data:image/webp;base64,${thumbnail}`)
    : "";

  const noto = await fetch(
    `${process.env.NEXT_PUBLIC_PFR_WEBSITE_BASE_URL}/assets/noto.ttf`,
  ).then((res) => res.arrayBuffer());

  const inter = await fetch(
    `${process.env.NEXT_PUBLIC_PFR_WEBSITE_BASE_URL}/assets/inter.ttf`,
  ).then((res) => res.arrayBuffer());

  return new ImageResponse(
    <div
      style={{ backgroundColor: "white" }}
      tw="flex flex-row w-full h-full items-center justify-center"
    >
      <div tw="flex flex-col w-1/2 items-center justify-center">
        <div tw="flex flex-col items-center justify-center">
          <PFRDefaultLogo height={70} width={210} />
        </div>
        <div tw="mt-12 flex flex-col items-center text-center mx-12">
          <p style={{ fontFamily: '"Inter"' }} tw="text-3xl tracking-tight">
            Research opportunity
          </p>
          <p style={{ fontFamily: '"Noto"' }} tw="text-xl mt-8 tracking-tight">
            {title}
          </p>
        </div>
        <span
          style={{
            background: "#E9C46A",
            color: "black",
            letterSpacing: "-0.025em",
          }}
          tw="mt-12 px-6 py-2 rounded-full"
        >
          Apply today
        </span>
      </div>
      <div tw="flex w-1/2 h-full">
        <img
          alt=""
          src={base64Thumbnail}
          style={{
            objectFit: "cover",
          }}
          tw="w-full h-full"
        />
      </div>
    </div>,
    {
      ...size,
      fonts: [
        {
          name: "Noto",
          data: noto,
          style: "normal",
        },
        {
          name: "Inter",
          data: inter,
          style: "normal",
        },
      ],
    },
  );
}
