import { MainLayout } from "@components/layouts/main.tsx";
import { Handlers, PageProps } from "$fresh/server.ts";
import { getPerformances, PerformanceRes } from "@lib/performance.ts";
import { AccessDeniedError } from "@lib/errors.ts";

export const handler: Handlers = {
  async GET(_, ctx) {
    const performances = await getPerformances();
    if (!("session" in ctx.state)) {
      throw new AccessDeniedError();
    }

    return ctx.render({ performances });
  },
};

function PerformanceLine(
  { maximum, data: [amount, min, average, max], url }: {
    maximum: number;
    url: string;
    data: readonly [number, number, number, number];
  },
) {
  return (
    <div
      class="mt-10 flex flex-col gap-2 bg-gray-900 px-4 py-2 rounded-2xl"
      style={{ background: "var(--light)" }}
    >
      <div style={{ color: "var(--foreground)" }}>
        {url}
      </div>
      <div class="flex gap-2">
        <span class="bg-gray-600 p-1 text-xs rounded-xl text-white">
          {Math.floor(average / 1000)}ms
        </span>
        <span class="bg-gray-600 p-1 text-xs rounded-xl text-white">
          {amount}x
        </span>
      </div>
      <div class="" style={{ maxWidth: "75vw" }}>
        <div
          class="h-2 bg-red-200 rounded"
          style={{
            width: `${Math.floor((max / maximum) * 100)}%`,
            borderRadius: "1rem 1rem 1rem 0px",
            minWidth: "5px",
          }}
        />
        <div
          class="h-2  bg-green-200 rounded"
          style={{
            width: `${Math.floor((average / maximum) * 100)}%`,
            borderStartEndRadius: "0px",
            borderRadius: "0px 0px 1rem 0px",
            minWidth: "5px",
          }}
        />
        <div
          class="h-2  bg-yellow-200 rounded"
          style={{
            width: `${Math.floor((min / maximum) * 100)}%`,
            borderRadius: "0px 0px 1rem 1rem",
            minWidth: "5px",
          }}
        />
      </div>
    </div>
  );
}

export default function Greet(
  { data: { performances }, url }: PageProps<{ performances: PerformanceRes }>,
) {
  return (
    <MainLayout url={url}>
      <h1 class="text-white text-4xl ">Performance</h1>

      {performances.res.map((r) => {
        return (
          <PerformanceLine
            maximum={performances.max}
            url={r.url}
            data={r.data}
          />
        );
      })}
    </MainLayout>
  );
}
