import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';
import { CalendarToday } from '@mui/icons-material';

import CustomPeriod from './CustomPeriod';
import { FormControl, InputAdornment, MenuItem, Select } from '@/mui/components';

import styles from './DateSelect.module.scss';

const CUSTOM_PERIOD_OPTION = {
  label: 'Custom period',
  value: 'custom_period',
};

function DateSelect({ enableCustomPeriod = false, stopRefreshInterval = null, resetRefreshInterval = null, ...props }) {
  const [open, setOpen] = useState(false);
  const [showCustomPeriodCalendars, setShowCustomPeriodCalendars] = useState(false);
  const [isCustomPeriodApplied, setIsCustomPeriodApplied] = useState(false);

  useEffect(() => {
    setShowCustomPeriodCalendars(!!props.filterDate?.isCustomPeriod);
    setIsCustomPeriodApplied(!!props.filterDate?.isCustomPeriod);
  }, [props.filterDate?.isCustomPeriod]);

  const options = [].concat(props.options);
  if (enableCustomPeriod) {
    options.push(CUSTOM_PERIOD_OPTION);
  }

  const handleOpen = () => {
    setOpen(true);

    if (stopRefreshInterval) {
      stopRefreshInterval();
    }
  };
  const handleClose = () => setOpen(false);
  const handleApplySelected = (value) => {
    props.setFilterDate(value);
    handleClose();
  };
  const handleApplyCustomPeriod = (value) => {
    const diff = dayjs(value.to).diff(value.from, 'days');
    const changesStringFrom = dayjs(value.from).subtract(diff, 'day');

    const period = {
      stringFrom: dayjs(value.from).format('YYYY-MM-DDT00:00:00'),
      stringTo: dayjs(value.to).format('YYYY-MM-DDT00:00:00'),
      change: {
        stringFrom: changesStringFrom.format('YYYY-MM-DDT00:00:00'),
        stringTo: dayjs(value.from).format('YYYY-MM-DDT00:00:00'),
      },
      dimension: 'HOUR',
      changeDimension: 'HOUR',
      isCustomPeriod: true,
    };
    handleApplySelected(period);
    setIsCustomPeriodApplied(true);
  };
  const handleChange = ({ target: { value } }) => {
    if (value === CUSTOM_PERIOD_OPTION.value) {
      setShowCustomPeriodCalendars(true);
    } else {
      handleApplySelected(value);
      setShowCustomPeriodCalendars(false);
      setIsCustomPeriodApplied(false);
    }
  };

  return (
    <FormControl variant="outlined" size="small">
      <Select
        variant="outlined"
        size="small"
        open={open}
        className={styles.Select}
        id="date-filter"
        value={isCustomPeriodApplied ? CUSTOM_PERIOD_OPTION.value : props.filterDate}
        onChange={handleChange}
        onOpen={handleOpen}
        onClose={(e) => {
          if (e.currentTarget.dataset?.value !== CUSTOM_PERIOD_OPTION.value) {
            handleClose();
          }

          if (resetRefreshInterval) {
            resetRefreshInterval();
          }
        }}
        startAdornment={
          <InputAdornment position="start">
            <CalendarToday fontSize="small" />
          </InputAdornment>
        }
      >
        {options.map((item) => {
          const children =
            item.value === CUSTOM_PERIOD_OPTION.value ? (
              <CustomPeriod
                key={item.label}
                label={CUSTOM_PERIOD_OPTION.label}
                from={isCustomPeriodApplied ? props.filterDate.stringFrom : null}
                to={isCustomPeriodApplied ? props.filterDate.stringTo : null}
                showCustomPeriodCalendars={showCustomPeriodCalendars}
                titleMode={!open}
                onPeriodSelect={handleApplyCustomPeriod}
              />
            ) : (
              item.label
            );

          return (
            <MenuItem key={item.label} value={item.value}>
              {children}
            </MenuItem>
          );
        })}
      </Select>
    </FormControl>
  );
}

DateSelect.propTypes = {
  filterDate: PropTypes.shape({
    stringFrom: PropTypes.string,
    stringTo: PropTypes.string,
    isCustomPeriod: PropTypes.bool,
  }).isRequired,
  setFilterDate: PropTypes.func.isRequired,
  options: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.shape({
        stringFrom: PropTypes.string,
        change: PropTypes.shape({
          stringFrom: PropTypes.string,
          stringTo: PropTypes.string,
        }),
      }),
    }),
  ).isRequired,
  enableCustomPeriod: PropTypes.bool,
  stopRefreshInterval: PropTypes.func,
  resetRefreshInterval: PropTypes.func,
};

export default DateSelect;
