import { Handlers, PageProps } from "$fresh/server.ts";
import { MainLayout } from "@components/layouts/main.tsx";
import { Article, getArticle } from "@lib/resource/articles.ts";
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/documents.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";

export const handler: Handlers<{ article: Article; session: unknown }> = {
  async GET(_, ctx) {
    const article = await getArticle(ctx.params.name);
    if (!article) {
      return ctx.renderNotFound();
    }
    return ctx.render({ article, session: ctx.state.session });
  },
};

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

  const { author = "", date = "" } = article.meta;

  const content = renderMarkdown(
    removeImage(article.content, article.meta.image),
  );

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

      <PageHero image={article.meta.image} thumbnail={article.meta.thumbnail}>
        <PageHero.Header>
          <PageHero.BackLink href="/articles" />
          {session && (
            <PageHero.EditLink
              href={`https://notes.max-richter.dev/Media/articles/${article.id}`}
            />
          )}
        </PageHero.Header>
        <PageHero.Footer>
          <PageHero.Title link={article.meta.link}>
            {article.name}
          </PageHero.Title>
          <PageHero.Subline
            entries={[
              author && {
                title: author,
                href: `/?q=${encodeURIComponent(author)}`,
              },
              date.toString(),
            ]}
          >
            {article.meta.rating && <Star rating={article.meta.rating} />}
          </PageHero.Subline>
        </PageHero.Footer>
      </PageHero>
      {article.tags.length > 0 && (
        <>
          <br />
          <HashTags tags={article.tags} />
        </>
      )}

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