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

export const handler: Handlers<{ article: ArticleResource; session: unknown }> =
  {
    async GET(_, ctx) {
      const article = await fetchResource<ArticleResource>(
        `articles/${ctx.params.name}.md`,
      );
      if (!article) {
        return ctx.renderNotFound();
      }
      return ctx.render({ article, session: ctx.state.session });
    },
  };

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

  const { author, datePublished, reviewRating, articleBody = "" } =
    article?.content || {};

  const content = renderMarkdown(
    removeImage(articleBody, article.image?.url),
  );

  const rating = reviewRating?.ratingValue &&
    parseRating(reviewRating.ratingValue);

  return (
    <MainLayout
      url={props.url}
      title={`Article > ${article.content.headline}`}
      context={article}
    >
      <RedirectSearchHandler />
      <KMenu type="main" context={article} />
      <MetaTags resource={article} />

      <PageHero
        image={article.image?.url}
        thumbhash={article.image?.thumbhash}
      >
        <PageHero.Header>
          <PageHero.BackLink href="/articles" />
          {session && (
            <PageHero.EditLink
              href={`https://notes.max-richter.dev/resources/articles/${article.name}`}
            />
          )}
        </PageHero.Header>
        <PageHero.Footer>
          <PageHero.Title link={article.content.url}>
            {article.content.headline}
          </PageHero.Title>
          <PageHero.Subline
            entries={[
              author?.name && {
                title: author.name,
                href: `/?q=${encodeURIComponent(author?.name)}`,
              },
              datePublished?.toString(),
            ]}
          >
            {rating && <Star rating={rating} />}
          </PageHero.Subline>
        </PageHero.Footer>
      </PageHero>
      {article.content?.keywords?.length && (
        <>
          <br />
          <HashTags tags={article.content.keywords} />
        </>
      )}

      <div class="px-8 text-white mt-10">
        {(article.content.url && isYoutubeLink(article.content.url)) && (
          <YoutubePlayer link={article.content.url} />
        )}
        <pre
          class="whitespace-break-spaces markdown-body"
          data-color-mode="dark"
          data-dark-theme="dark"
          // deno-lint-ignore react-no-danger
          dangerouslySetInnerHTML={{ __html: content || "" }}
        />
      </div>
    </MainLayout>
  );
}
