import { CSS, render } from "@deno/gfm";
import { Head } from "$fresh/runtime.ts";
import { Handlers, PageProps } from "$fresh/server.ts";

import { getPost, Post } from "../../lib/posts.ts";
import { LuClock } from "@preact-icons/lu";

export const handler: Handlers<Post> = {
  async GET(_req, ctx) {
    try {
      const post = await getPost(ctx.params.slug);
      return post.publishedAt ? ctx.render(post) : ctx.renderNotFound();
    } catch (err) {
      console.error(err);
      return ctx.renderNotFound();
    }
  },
};

export default function PostPage(props: PageProps<Post>) {
  const post = props.data;
  return (
    <>
      <Head>
        <style dangerouslySetInnerHTML={{ __html: CSS }} />
      </Head>
      <div class="min-h-screen p-4 md:p-8">
        <div class="max-w-3xl mx-auto">
          <div class="p-4 md:p-8">
            {/* Header section */}
            <h1 class="text-4xl md:text-5xl font-bold text-primary mb-6">
              {post.title}
            </h1>

            <div class="flex flex-wrap items-center gap-4 mb-6">
              {/* Date with clock icon */}
              <div class="flex items-center flex-row gap-2 text-base-content opacity-75">
                <LuClock />
                <time>
                  {post.publishedAt!.toLocaleDateString("en-us", {
                    month: "long",
                    day: "numeric",
                    year: "numeric",
                  })}
                </time>
              </div>

              {/* Back button */}
              <a href="/posts" class="btn btn-outline btn-primary btn-sm">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-5 w-5 mr-1"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M11 17l-5-5m0 0l5-5m-5 5h12"
                  />
                </svg>
                Back
              </a>
            </div>

            {/* Divider line */}
            <div class="divider"></div>

            {/* Content section */}
            <div
              class="max-w-none prose"
              data-color-mode="dark"
              data-dark-theme="dark"
              dangerouslySetInnerHTML={{ __html: render(post.content) }}
            />
          </div>
        </div>
      </div>
    </>
  );
}
