import { Heading, Button, FormControl } from "@chakra-ui/react";
import { TimePickerRange } from "utils";
import { useState } from "react";
import { DateTimeField } from "./date_time_field";
import { DateTime, Interval } from "luxon";

export interface AbsoluteTimePickerProps {
  close: () => void;
  timeRange: TimePickerRange;
  handleChange: (timePickerRange: TimePickerRange) => void;
}

export function AbsoluteTimePicker(props: AbsoluteTimePickerProps) {
  const [fromValue, setFromValue] = useState(
    props.timeRange.absolute?.start?.toISO() ?? ""
  );
  const [toValue, setToValue] = useState(
    props.timeRange.absolute?.end?.toISO() ?? ""
  );

  const onApply = () => {
    const fromDateTime = DateTime.fromISO(fromValue);
    if (!fromDateTime.isValid) {
      return;
    }

    const toDateTime = DateTime.fromISO(toValue);
    if (!toDateTime.isValid) {
      return;
    }

    const timePickerRange = TimePickerRange.fromAbsolute(
      Interval.fromDateTimes(fromDateTime, toDateTime)
    );
    props.handleChange(timePickerRange);
    props.close();
  };

  return (
    <FormControl width="300px">
      <Heading fontSize="medium">Absolute time ranges</Heading>

      <DateTimeField value={fromValue} onChange={setFromValue} label="From" />
      <DateTimeField value={toValue} onChange={setToValue} label="To" />

      <Button onClick={onApply} marginTop={4}>
        Apply time range
      </Button>
    </FormControl>
  );
}
