import { DateTime } from "luxon";
import { AppTimeRanges } from "utils";
import { IconButton, Grid, Box } from "@chakra-ui/react";
import { TimePickerToggle } from "./time_picker_toggle";
import { RepeatIcon } from "@chakra-ui/icons";

export interface QueryControlsProps {
  appTimeRanges: AppTimeRanges;
  loading: boolean;
  error: any;
  queryDurationMs: number;
}

export function QueryControls(props: QueryControlsProps) {
  const queryStartText = props.appTimeRanges.queryRange.start
    .toLocal()
    .toLocaleString(DateTime.DATETIME_SHORT_WITH_SECONDS);
  const queryEndText = props.appTimeRanges.queryRange.end
    .toLocal()
    .toLocaleString(DateTime.DATETIME_SHORT_WITH_SECONDS);

  let statusMessage;
  if (props.error) {
    statusMessage = (
      <div>Loading failed with error: {props.error.toString()}</div>
    );
  } else if (props.loading) {
    statusMessage = (
      <div>
        <div>
          Loading data from {queryStartText} - {queryEndText}
        </div>
        <div>This can take up to 2 minutes...</div>
      </div>
    );
  } else {
    let queryDurationMessage = null;
    if (props.queryDurationMs > 0) {
      const trimmedSeconds = props.queryDurationMs / 1000;

      queryDurationMessage = (
        <div>Query ran in {trimmedSeconds.toFixed(2)} seconds.</div>
      );
    }
    statusMessage = (
      <div>
        <div>
          Showing data from {queryStartText} - {queryEndText}.
        </div>
        <div>{queryDurationMessage}</div>
      </div>
    );
  }

  return (
    <Grid
      templateColumns="1fr repeat(2, max-content)"
      gap={2}
      padding="5px"
      borderBottom="solid rgb(242, 242, 242) 1px"
      marginBottom="15px"
      minHeight="32px"
    >
      <Box color="grey">{statusMessage}</Box>
      <TimePickerToggle
        timeRange={props.appTimeRanges.timePickerRange}
        handleChange={props.appTimeRanges.setTimePickerRange}
      />
      <IconButton
        onClick={props.appTimeRanges.refreshQueryRange}
        aria-label="Refresh"
        icon={<RepeatIcon />}
        isLoading={props.loading}
      />
    </Grid>
  );
}
