import {
  Button,
  DialogActions,
  DialogContent,
  Grid2 as Grid,
  TextField,
  Theme,
  Typography
} from "@mui/material";
import moment, { Moment } from "moment";
import { DateRange as DateIcon } from "@mui/icons-material";
import React, { useEffect, useState } from "react";
import ResponsiveDialog from "common/ResponsiveDialog";
import { DateRangePreset, GetDefaultDateRange, SetDefaultPreset } from "./DateRange";
import { useThemeType } from "hooks";
import { makeStyles } from "@mui/styles";
import { cloneDeep } from "lodash";
import { color } from "@mui/system";

interface Props {
  startDate: Moment;
  endDate: Moment;
  updateDateRange: (start: Moment, end: Moment, live: boolean) => void;
}

// Define a type similar to DateRange<Moment>
type DateRange<T> = [T | null, T | null];

const useStyles = makeStyles((_theme: Theme) => {
  return ({
    activeButtonLight: {
      border: "1px solid black",
      color: "black"
    },
    acitveButtonDark: {
      border: "1px solid white",
      color: "white"
    }
  })
});

export default function TimeBar(props: Props) {
  const { updateDateRange, startDate, endDate } = props;
  const defaultDateRange = GetDefaultDateRange();
  const [dateRangeDialog, setDateRangeDialog] = useState(false);
  const [dateRange, setDateRange] = useState<DateRange<Moment>>([
    defaultDateRange.start,
    defaultDateRange.end
  ]);

  const [activeView, setActiveView] = useState<DateRangePreset>();
  const classes = useStyles();
  const themeType = useThemeType();

  const submitDateRange = () => {
    const startDate = dateRange[0] ? dateRange[0].clone() : moment();
    const endDate = dateRange[1] ? dateRange[1].add(1, "day").clone() : moment(); //add 1 day to the end time to include that day rather than have it be the cutoff
    updateDateRange(startDate, endDate, false);
    setDateRangeDialog(false);
    setActiveView("selectRange");
  };

  useEffect(() => {
    let hourDiff = moment(endDate)
      .diff(moment(startDate), "hours", true)
      .toFixed(4);
    let dayDiff = moment(endDate)
      .diff(moment(startDate), "days", true)
      .toFixed(4);
    let monthDiff = moment(endDate)
      .diff(moment(startDate), "months", true)
      .toFixed(4);
    if (hourDiff === "1.0000") {
      setActiveView("pastHour");
    } else if (dayDiff === "1.0000") {
      setActiveView("pastDay");
    } else if (dayDiff === "7.0000") {
      setActiveView("pastWeek");
    } else if (monthDiff === "1.0000") {
      setActiveView("pastMonth");
    } else {
      setActiveView("selectRange");
    }
  }, [startDate, endDate]);

  const datePickerDialog = () => {
    return (
      <ResponsiveDialog
        open={dateRangeDialog}
        onClose={() => setDateRangeDialog(false)}
        aria-labelledby="date-range-dialog">
        <DialogContent>
          <TextField
            fullWidth
            margin="normal"
            type="date"
            label="Start Time"
            value={dateRange[0]?.format("YYYY-MM-DD")}
            onChange={e => {
              let range = cloneDeep(dateRange)
              range[0] = moment(e.target.value)
              setDateRange(range)
            }}
          />
          <TextField
            fullWidth
            margin="normal"
            type="date"
            label="End Time"
            value={dateRange[1]?.format("YYYY-MM-DD")}
            onChange={e => {
              let range = cloneDeep(dateRange)
              range[1] = moment(e.target.value)
              setDateRange(range)
            }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDateRangeDialog(false)} color="primary">
            Close
          </Button>
          <Button onClick={submitDateRange} color="primary">
            Submit
          </Button>
        </DialogActions>
      </ResponsiveDialog>
    );
  };

  return (
    <React.Fragment>
      {datePickerDialog()}
      <Grid container direction="row" spacing={1} wrap="nowrap">
        <Grid>
          <Button
            style={{ borderRadius: "25px" }}
            className={
              activeView === "pastHour"
                ? themeType === "light"
                  ? classes.activeButtonLight
                  : classes.acitveButtonDark
                : ""
            }
            onClick={() => {
              updateDateRange(moment().subtract(1, "hour"), moment(), false);
              SetDefaultPreset("pastHour");
            }}>
            <Typography style={{ fontWeight: 650 }}>1H</Typography>
          </Button>
        </Grid>
        <Grid>
          <Button
            style={{ borderRadius: "25px" }}
            className={
              activeView === "pastDay"
                ? themeType === "light"
                  ? classes.activeButtonLight
                  : classes.acitveButtonDark
                : ""
            }
            onClick={() => {
              updateDateRange(moment().subtract(1, "day"), moment(), false);
              SetDefaultPreset("pastDay");
            }}>
            <Typography style={{ fontWeight: 650 }}>1D</Typography>
          </Button>
        </Grid>
        <Grid>
          <Button
            style={{ borderRadius: "25px" }}
            className={
              activeView === "pastWeek"
                ? themeType === "light"
                  ? classes.activeButtonLight
                  : classes.acitveButtonDark
                : ""
            }
            onClick={() => {
              updateDateRange(moment().subtract(1, "week"), moment(), false);
              SetDefaultPreset("pastWeek");
            }}>
            <Typography style={{ fontWeight: 650 }}>1W</Typography>
          </Button>
        </Grid>
        <Grid>
          <Button
            style={{ borderRadius: "25px" }}
            className={
              activeView === "pastMonth"
                ? themeType === "light"
                  ? classes.activeButtonLight
                  : classes.acitveButtonDark
                : ""
            }
            onClick={() => {
              updateDateRange(moment().subtract(1, "month"), moment(), false);
              SetDefaultPreset("pastMonth");
            }}>
            <Typography style={{ fontWeight: 650 }}>1M</Typography>
          </Button>
        </Grid>
        <Grid>
          <Button
            style={{ borderRadius: "25px" }}
            className={
              activeView === "selectRange"
                ? themeType === "light"
                  ? classes.activeButtonLight
                  : classes.acitveButtonDark
                : ""
            }
            onClick={() => {
              setDateRangeDialog(true);
            }}>
            <DateIcon />
          </Button>
        </Grid>
      </Grid>
    </React.Fragment>
  );
}
