import gql from "gql-tag";
import { Requests } from "../components/Requests";
import { useParams } from "react-router-dom";
import { useQuery } from "urql";
import { ProjectApiKey } from "../types";
import { Spinner } from "../components/Spinner";
import { KEY_COMPONENT, KEY_KEY } from "../testing";

const apiKeysQuery = gql`
  query ApiKeyQuery($id: ID, $projectId: ID) {
    apiKeys(where: { id: $id, projectId: $projectId }) {
      keys {
        id
        name
        key
      }
    }
  }
`;

export function ApiKey() {
  const params = useParams();

  const [result] = useQuery({
    query: apiKeysQuery,
    variables: { id: params.apiKeyId, projectId: params.projectId },
  });

  const apiKey = (result?.data?.apiKeys?.keys || [])[0] as ProjectApiKey;

  return (
    <div className="flex flex-col w-full p-5" id={KEY_COMPONENT}>
      <div className="border-b border-gql-vis-grey-2 p-5">
        <div className="text-center mx-auto text-center text-gql-vis-darkblue">
          <h2 className="text-4xl font-bold">{apiKey?.name}</h2>
          <p className="text-sm mt-3" id={KEY_KEY}>
            {apiKey?.key}
          </p>
        </div>
      </div>
      <div className="m-5 pb-5">
        <div className="flex flex-col gap-5 p-5">
          <h3 className="text-3xl font-bold text-gql-vis-darkblue">Requests</h3>
          <div>
            <p>List of the latest requests.</p>
          </div>
        </div>

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