import { useQuery } from "urql";
import { AllApiKeysQueryDocument } from "../../gql-codegen/graphql";
import {
  ButtonType,
  DefaultButton,
} from "./_organisms/_molecules/_atoms/DefaultButtonElement";
import { Spinner } from "../Spinner";
import { useNavigate, useParams } from "react-router-dom";
import { ProjectApiKey } from "../../types";
import { CREATE_KEY_BUTTON } from "../../testing";

const tableStyles = {
  sticky: "sticky top-0 z-10",
  headerCell:
    "border-b border-gray-300 bg-opacity-75 py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900",
};

function TableHeader() {
  return (
    <thead>
      <tr className={tableStyles.sticky}>
        <th scope="col" className={`${tableStyles.headerCell} sm:pl-6 lg:pl-8`}>
          Name
        </th>
        <th scope="col" className={`${tableStyles.headerCell} sm:pl-6 lg:pl-8`}>
          # Requests
        </th>
      </tr>
    </thead>
  );
}

const rowStyles = {
  cell: "border-b border-gray-200 whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900",
  link: "text-indigo-600 hover:text-indigo-900",
};

function TableRow({ projectApiKey }: { projectApiKey: ProjectApiKey }) {
  const navigate = useNavigate();
  const params = useParams();

  return (
    <tr
      key={projectApiKey.id}
      className="hover:cursor-pointer hover:underline"
      onClick={() => {
        navigate(
          `/company/${params.companyId}/project/${params.projectId}/api-key/${projectApiKey.id}`,
        );
      }}
    >
      <td className={`${rowStyles.cell} sm:pl-6 lg:pl-8`}>
        {projectApiKey.name}
      </td>
      <td className={`${rowStyles.cell} sm:pl-6 lg:pl-8`}>
        {projectApiKey.requests?.length}
      </td>
    </tr>
  );
}

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

  const [result] = useQuery({
    query: AllApiKeysQueryDocument,
    variables: {
      where: {
        projectId: params.projectId,
      },
    },
  });

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

  return (
    <>
      <div className="flex flex-col w-full h-full align-top content-start gap-5">
        <div className="flex flex-row w-full space-between">
          <h3 className="text-3xl font-bold text-gql-vis-darkblue">API Keys</h3>
          <div className="ml-auto">
            <DefaultButton
              id={CREATE_KEY_BUTTON}
              text="Create API Key"
              route={`/company/${params.companyId}/project/${params.projectId}/api-key/create`}
              type={ButtonType.SUCCESS}
            />
          </div>
        </div>
        <div>
          <p>An overview of all your API Keys</p>
        </div>
        <div className="flow-root">
          <div>
            <div className="inline-block min-w-full align-middle max-h-96 border border-gray-300 rounded-xl">
              <table className="min-w-full bg-white border-separate border-spacing-0 max-h-[500] rounded-xl">
                <TableHeader />
                <tbody className="max-h-[500]">
                  {apiKeys.map((projectApiKey: ProjectApiKey) => (
                    <TableRow
                      key={projectApiKey.id}
                      projectApiKey={projectApiKey}
                    />
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
        {result.fetching ? (
          <div className="flex justify-center align-center mx-auto pt-20">
            <Spinner></Spinner>
          </div>
        ) : (
          <></>
        )}
      </div>
    </>
  );
}
