import { Handlers, PageProps } from "$fresh/server.ts";
import { MainLayout } from "@components/layouts/main.tsx";
import { getMovie, Movie } from "@lib/resource/movies.ts";
import { RecipeHero } from "@components/RecipeHero.tsx";
import { HashTags } from "@components/HashTags.tsx";
import { renderMarkdown } from "@lib/documents.ts";
import { KMenu } from "@islands/KMenu.tsx";
import { RedirectSearchHandler } from "@islands/Search.tsx";

export const handler: Handlers<Movie | null> = {
  async GET(_, ctx) {
    const movie = await getMovie(ctx.params.name);
    return ctx.render({ movie, session: ctx.state.session });
  },
};

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

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

  const content = renderMarkdown(movie.description || "");

  return (
    <MainLayout url={props.url} title={`Movie > ${movie.name}`} context={movie}>
      <RedirectSearchHandler />
      <KMenu type="main" context={movie} />
      <RecipeHero
        data={movie}
        subline={[
          author && {
            title: author,
            href: `/?q=${encodeURIComponent(author)}`,
          },
          date.toString(),
        ]}
        editLink={session
          ? `https://notes.max-richter.dev/Media/movies/${movie.id}`
          : ""}
        backlink="/movies"
      />
      {movie.tags.length > 0 && (
        <>
          <br />
          <HashTags tags={movie.tags} />
        </>
      )}
      <div class="px-8 text-white mt-10">
        {movie?.description?.length > 80
          ? <h2 class="text-4xl font-bold mb-4">Review</h2>
          : <></>}
        <pre
          class="whitespace-break-spaces"
          dangerouslySetInnerHTML={{ __html: content || "" }}
        >
          {content}
        </pre>
      </div>
    </MainLayout>
  );
}
