import {
  Button,
  useBoolean,
  useOutsideClick,
  Flex,
  Box,
} from "@chakra-ui/react";
import { TimePicker } from "../time_picker";
import { useRef } from "react";
import { TimePickerRange } from "utils";
import { TriangleUpIcon, TriangleDownIcon, TimeIcon } from "@chakra-ui/icons";

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

export function TimePickerToggle(props: TimePickerToggleProps) {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const timePickerRef = useRef<HTMLDivElement>(null);
  const [isOpen, setOpen] = useBoolean(false);
  useOutsideClick({
    ref: timePickerRef,
    handler: (e) => {
      if (e.target === buttonRef.current) {
        return;
      }
      setOpen.off();
    },
  });

  let buttonText = props.timeRange.toString();

  const colorScheme = isOpen ? "green" : "blue";
  const rightIcon = isOpen ? <TriangleUpIcon /> : <TriangleDownIcon />;

  return (
    <Flex direction="column">
      <Button
        onClick={setOpen.toggle}
        colorScheme={colorScheme}
        ref={buttonRef}
        leftIcon={<TimeIcon />}
        rightIcon={rightIcon}
      >
        {buttonText}
      </Button>
      <Box position="relative">
        <TimePicker
          ref={timePickerRef}
          close={setOpen.off}
          timeRange={props.timeRange}
          handleChange={props.handleChange}
          open={isOpen}
        />
      </Box>
    </Flex>
  );
}
