import { useContext } from "react";
import { Projects } from "../components/_layouts/Projects";
import DashboardCard from "../components/_layouts/_organisms/_molecules/DashboardCard";
import { useQuery } from "urql";
import { UserContext } from "../contexts/UserContext";
import { Company, CompanyQueryDocument } from "../gql-codegen/graphql";
import {
  COMPANY_AVG_CONTENT_LENGTH,
  COMPANY_AVG_EXECUTION,
  COMPANY_COMPONENT,
  COMPANY_TOTAL_PROJECTS,
  COMPANY_TOTAL_REQUEST,
  DASHBOARD_COMPONENT,
} from "../testing";

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

  const userStore = useContext(UserContext);
  const companyId = userStore.getUser()?.companies?.[0]?.id;

  const [result] = useQuery({
    query: CompanyQueryDocument,
    variables: {
      id: companyId || "",
      dateRange: { from: from.toISOString(), to: to.toISOString() },
    },
  });

  const companies = (result?.data?.companies?.companies || []) as Company[];
  const company = companies[0];

  return (
    <div className="flex flex-col gap-10 w-full " id={DASHBOARD_COMPONENT}>
      <div id={COMPANY_COMPONENT} data-companyId={company?.id}>
        <h2 className="text-4xl text-center font-bold text-gql-vis-darkblue">
          Company: {company?.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={COMPANY_TOTAL_REQUEST}
          title="Total Daily Requests"
          value={company?.aggregate?.requestCount?.toString() || "0"}
        />
        <DashboardCard
          id={COMPANY_TOTAL_PROJECTS}
          title="Total Projects"
          value={company?.aggregate?.projectCount?.toString() || "0"}
        />
        <DashboardCard
          id={COMPANY_AVG_EXECUTION}
          title="Daily Avg Execution(ms)"
          value={Number(
            company?.aggregate?.averageRequestExecutionTime || 0,
          ).toFixed(2)}
        />
        <DashboardCard
          id={COMPANY_AVG_CONTENT_LENGTH}
          title="Daily Avg Content Length"
          value={"N/A"}
        />
      </div>
      <Projects />
    </div>
  );
}
