import { MainLayout } from "@components/layouts/main.tsx";
import { PageProps } from "fresh";
import { AccessDeniedError } from "@lib/errors.ts";
import { getLogs, Log } from "@lib/log/index.ts";
import { formatDate } from "@lib/string.ts";
import { renderMarkdown } from "@lib/markdown.ts";
import { define } from "../../../utils.ts";

const renderLog = (t: unknown) =>
  renderMarkdown(`\`\`\`js
${typeof t === "string" ? t : JSON.stringify(t, null, 2).trim()}
\`\`\``);

export const handler = define.handlers({
  async GET(ctx) {
    const logs = await getLogs();
    if (!("session" in ctx.state)) {
      throw new AccessDeniedError();
    }
    return {
      data: {
        logs: logs.map((l) => {
          return {
            ...l,
            html: l.args.map(renderLog).join("<br/>"),
          };
        }),
      },
    };
  },
});

function LogLine(
  { log }: {
    log: Log & { html?: string };
  },
) {
  return (
    <div
      class="mt-4 flex flex-col gap-2 bg-gray-900 px-4 py-2 rounded-2xl max-w-3xl"
      style={{ background: "var(--light)" }}
    >
      <div class="flex gap-2">
        <span class="bg-gray-600 py-1 px-2 text-xs rounded-xl text-white">
          {log.date.getHours().toString().padStart(2, "0")}:{log.date
            .getMinutes().toString().padStart(2, "0")}:{log.date.getSeconds()
            .toString().padStart(2, "0")} {formatDate(log.date)}
        </span>
        <span class="bg-gray-600 py-1 px-2 text-xs rounded-xl text-white">
          {log.scope}
        </span>
        <span class="bg-gray-600 py-1 px-2 text-xs rounded-xl text-white">
          {log.level}
        </span>
      </div>
      <div
        class="text-white"
        // deno-lint-ignore react-no-danger
        dangerouslySetInnerHTML={{ __html: log.html ?? "" }}
      />
    </div>
  );
}

export default function Greet(
  { data: { logs }, url }: PageProps<{ logs: Log[] }>,
) {
  return (
    <MainLayout url={url}>
      <h1 class="text-white text-4xl">Logs</h1>

      {logs.map((r) => {
        return (
          <LogLine
            log={r}
          />
        );
      })}
    </MainLayout>
  );
}
