import { ApiKeys } from "../components/_layouts/ApiKeys";
import { Spinner } from "../components/Spinner";

import { useQuery } from "urql";
import { AllProjectsQueryDocument, type Project } from "../gql-codegen/graphql";
import { useParams } from "react-router-dom";
import DashboardCard from "../components/_layouts/_organisms/_molecules/DashboardCard";
import {
  PROJECT_AVG_CONTENT_LENGTH,
  PROJECT_AVG_EXECUTION,
  PROJECT_COMPONENT,
  PROJECT_TOTAL_KEYS,
  PROJECT_TOTAL_REQUEST,
} from "../testing";

export function Project() {
  const params = useParams();
  const from = new Date();
  from.setUTCHours(0, 0, 0, 0);
  const to = new Date();
  to.setHours(23, 59, 59, 999);

  const [result] = useQuery({
    query: AllProjectsQueryDocument,
    variables: {
      where: {
        id: params.projectId,
      },
      dateRange: {
        from: from.toISOString(),
        to: to.toISOString(),
      },
    },
  });

  const project = (result?.data?.projects?.projects || [])[0] as Project;

  return (
    <div
      className="flex flex-col w-full p-5 gap-5"
      id={PROJECT_COMPONENT}
      data-id={project?.id}
    >
      <div>
        <h2 className="text-4xl text-center font-bold text-gql-vis-darkblue">
          Project: {project?.name}
        </h2>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 xl:flex xl:flex-row gap-5 w-full justify-between">
        <DashboardCard
          id={PROJECT_TOTAL_REQUEST}
          title="Total Daily Requests"
          value={project?.aggregate?.requestCount?.toString() || "0"}
        />
        <DashboardCard
          id={PROJECT_TOTAL_KEYS}
          title="Total Keys"
          value={project?.apiKeys?.length?.toString() || "0"}
        />
        <DashboardCard
          id={PROJECT_AVG_EXECUTION}
          title="Daily Avg Execution(ms)"
          value={
            project?.aggregate?.averageRequestExecutionTime
              ? (project?.aggregate?.averageRequestExecutionTime || 0).toFixed(
                  2,
                )
              : "0"
          }
        />
        <DashboardCard
          id={PROJECT_AVG_CONTENT_LENGTH}
          title="Daily Avg Content Length"
          value="N/A"
        />
      </div>

      <div className="w-full h-full">
        {result.fetching ? (
          <div className="flex justify-center align-center mx-auto pt-20">
            <Spinner></Spinner>
          </div>
        ) : (
          <ApiKeys />
        )}
      </div>
    </div>
  );
}
