import React from "react";
import { ItemTable } from "components/item_table";
import { Service } from "plucky_client/plucky";
import { QueryControls } from "components/query_controls";
import { AppTimeRanges } from "utils";
import { useItems } from "plucky_client/hooks";
import { Box } from "@chakra-ui/react";
import { H1 } from "components/headings";

export interface ItemsProps {
  service: Service;
  appTimeRanges: AppTimeRanges;
}

export function ItemsPage(props: ItemsProps) {
  const { data, error, loading } = useItems(
    props.service.serviceId,
    props.service.stageId,
    props.appTimeRanges.queryRange.start.toJSDate(),
    props.appTimeRanges.queryRange.end.toJSDate()
  );

  let itemTable = null;
  if (data) {
    itemTable = (
      <ItemTable
        data={data}
        queryRange={props.appTimeRanges.queryRange}
        serviceURLSlug={props.service.urlSlug}
      />
    );
  }

  const queryDurationMs = data ? data.queryTimeMs : 0;

  return (
    <Box>
      <H1>
        {props.service.displayName} - {props.service.displayStage} - Items
      </H1>

      <QueryControls
        appTimeRanges={props.appTimeRanges}
        loading={loading}
        error={error}
        queryDurationMs={queryDurationMs}
      />

      {itemTable}
    </Box>
  );
}
