import { useQuery } from "urql";
import { useNavigate } from "react-router-dom";
import { useContext } from "react";
import {
  AllProjectsQueryDocument,
  Project,
  ProjectsResponse,
} from "../../gql-codegen/graphql";
import { ProjectContext } from "../../contexts/ProjectContext";
import { Spinner } from "../Spinner";
import { UserContext } from "../../contexts/UserContext";
import { CREATE_PROJECT_BUTTON, PROJECTS_COMPONENT } 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",
  lastHeaderCell: "border-b border-gray-300 bg-opacity-75 py-3.5 pl-3 pr-4",
};

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`}>
          # API Keys
        </th>
        <th scope="col" className={`${tableStyles.headerCell} sm:pr-6 lg:pr-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",
  lastCell:
    "border-b border-gray-200 relative whitespace-nowrap py-4 pr-4 pl-3 text-right text-sm font-medium sm:pr-8 lg:pr-8",
  link: "text-indigo-600 hover:text-indigo-900",
};

function TableRow({
  project,
  companyId,
}: {
  project: Project;
  companyId?: string;
}) {
  const navigate = useNavigate();

  return (
    <tr
      data-name={project.name}
      key={project.id}
      className="hover:cursor-pointer hover:underline"
      onClick={() => {
        navigate(`/company/${companyId}/project/${project.id}`);
      }}
    >
      <td className={`${rowStyles.cell} sm:pl-6 lg:pl-8`}>{project.name}</td>
      <td className={`${rowStyles.cell} sm:pl-6 lg:pl-8`}>
        {project.aggregate.apiKeyCount}
      </td>
      <td className={`${rowStyles.cell} sm:pl-6 lg:pl-8`}>
        {project.aggregate.requestCount}
      </td>
    </tr>
  );
}

function SpinnerComponent() {
  return (
    <div className="flex justify-center align-center mx-auto pt-20">
      <Spinner></Spinner>
    </div>
  );
}

export function Projects({ companyId }: { companyId?: string }) {
  const navigate = useNavigate();
  const userState = useContext(UserContext);

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

  const user = userState.getUser();
  const company = user?.companies?.[0];

  const projectStore = useContext(ProjectContext);
  const [result] = useQuery<{ projects: ProjectsResponse }>({
    query: AllProjectsQueryDocument,
    variables: {
      where: { companyId: company?.id },
      dateRange: {
        from: from.toISOString(),
        to: to.toISOString(),
      },
    },
  });

  projectStore.addProjects(
    (result?.data?.projects.projects || []) as Project[],
  );

  const projects = projectStore.getProjects();

  return (
    <div>
      <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-4xl font-bold text-gql-vis-darkblue">Projects</h3>
          <p className="ml-auto">
            <button
              id={CREATE_PROJECT_BUTTON}
              onClick={() => navigate(`/company/${company?.id}/project/create`)}
              type="button"
              className="flex justify-center rounded-md border border-transparent bg-green-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2"
            >
              Create
            </button>
          </p>
        </div>

        <div>
          <p>An overview of all your projects</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]" id={PROJECTS_COMPONENT}>
                  {projects.map((p: Project) => (
                    <TableRow
                      key={p.id}
                      project={p}
                      companyId={companyId || company?.id}
                    />
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {result.fetching ? <SpinnerComponent /> : <></>}
      </div>
    </div>
  );
}
