import { PageProps, RouteContext } from "$fresh/server.ts";
import { MainLayout } from "@components/layouts/main.tsx";
import { ReviewResource } from "@lib/marka/schema.ts";
import { removeImage, renderMarkdown } from "@lib/markdown.ts";
import { KMenu } from "@islands/KMenu.tsx";
import { RedirectSearchHandler } from "@islands/Search.tsx";
import { Recommendations } from "@islands/Recommendations.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";

export default async function Greet(
  props: PageProps<{ movie: ReviewResource; session: Record<string, string> }>,
  ctx: RouteContext,
) {
  const movie = await fetchResource<ReviewResource>(
    `movies/${ctx.params.name}.md`,
  );
  const session = ctx.state.session;

  if (!movie) {
    return ctx.renderNotFound();
  }

  const { author, datePublished, reviewBody = "", reviewRating } =
    movie.content;

  const content = renderMarkdown(
    removeImage(reviewBody, movie.content.image),
  );

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

  return (
    <MainLayout url={props.url} title={`Movie > ${movie.name}`} context={movie}>
      <RedirectSearchHandler />
      <KMenu type="main" context={movie} />
      <MetaTags resource={movie} />
      <PageHero
        image={movie.image?.url}
        thumbhash={movie.image?.thumbhash}
      >
        <PageHero.Header>
          <PageHero.BackLink href="/movies" />
          {session && (
            <PageHero.EditLink
              href={`https://notes.max-richter.dev/resources/movies/${movie.name}`}
            />
          )}
        </PageHero.Header>
        <PageHero.Footer>
          <PageHero.Title>
            {movie?.content?.itemReviewed?.name || movie?.name}
          </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>
      {movie.name && (
        <Recommendations
          id={movie.name}
          type="movie"
        />
      )}
      <div class="px-8 text-white mt-10">
        {reviewBody?.length > 80 && (
          <h2 class="text-4xl font-bold mb-4">Review</h2>
        )}
        <pre
          class="whitespace-break-spaces"
          // deno-lint-ignore react-no-danger
          dangerouslySetInnerHTML={{ __html: content || "" }}
        />
      </div>
    </MainLayout>
  );
}
