import { Handlers, PageProps } from "$fresh/server.ts";
import { MainLayout } from "@components/layouts/main.tsx";
import { HashTags } from "@components/HashTags.tsx";
import { removeImage, renderMarkdown } from "@lib/markdown.ts";
import { RedirectSearchHandler } from "@islands/Search.tsx";
import { KMenu } from "@islands/KMenu.tsx";
import PageHero from "@components/PageHero.tsx";
import { Star } from "@components/Stars.tsx";
import { MetaTags } from "@components/MetaTags.tsx";
import { parseRating } from "@lib/helpers.ts";
import { fetchResource } from "@lib/marka/index.ts";
import { ReviewResource } from "@lib/marka/schema.ts";

export const handler: Handlers<{ serie: ReviewResource; session: unknown }> = {
  async GET(_, ctx) {
    const serie = await fetchResource(`series/${ctx.params.name}.md`);

    if (!serie) {
      return ctx.renderNotFound();
    }
    return ctx.render({ serie, session: ctx.state.session });
  },
};

export default function Greet(
  props: PageProps<{ serie: ReviewResource; session: Record<string, string> }>,
) {
  const { serie, session } = props.data;

  const { author = "", date = "", reviewBody } = serie?.content || {};

  const content = renderMarkdown(
    removeImage(reviewBody, serie.image?.url),
  );

  return (
    <MainLayout
      url={props.url}
      title={`Serie > ${serie.content?.name}`}
      context={serie}
    >
      <RedirectSearchHandler />
      <KMenu type="main" context={serie} />

      <MetaTags resource={serie} />
      <PageHero
        image={serie.image?.url}
        thumbhash={serie.image?.thumbhash}
      >
        <PageHero.Header>
          <PageHero.BackLink href="/series" />
          {session && (
            <PageHero.EditLink
              href={`https://notes.max-richter.dev/resources/series/${serie.name}`}
            />
          )}
        </PageHero.Header>
        <PageHero.Footer>
          <PageHero.Title>{serie.name}</PageHero.Title>
          <PageHero.Subline
            entries={[
              author && {
                title: author,
                href: `/?q=${encodeURIComponent(author)}`,
              },
              date.toString(),
            ]}
          >
            {serie.content?.reviewRating && (
              <Star
                rating={parseRating(serie.content?.reviewRating?.ratingValue)}
              />
            )}
          </PageHero.Subline>
        </PageHero.Footer>
      </PageHero>
      {serie.content?.tags?.length > 0 && (
        <>
          <br />
          <HashTags tags={serie.content?.tags} />
        </>
      )}
      <div class="px-8 text-white mt-10">
        {serie?.content?.reviewBody?.length > 80
          ? <h2 class="text-4xl font-bold mb-4">Review</h2>
          : <></>}
        <pre
          class="whitespace-break-spaces"
          dangerouslySetInnerHTML={{ __html: content || "" }}
        >
          {content}
        </pre>
      </div>
    </MainLayout>
  );
}
