import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';

import { DAY_OPTIONS_WEEKLY, RECURRENCE_LIST, RECURRENCE_VALUES, TIME_OPTIONS } from '../../../../constants';
import { KEY_ENTER } from '@/modules/@common/constants/keyCodes';
import { emailRegExp } from '@/modules/@common/constants/validation';

import { getUserEmailSelector, getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

import {
  Autocomplete,
  Button,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Typography,
} from '@/mui/components';

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

const DAY_OPTIONS = Array.from({ length: 31 }, (value, index) => index + 1).map((item) => ({
  label: item,
  value: item,
}));

function ScheduleDialog(props) {
  const userEmail = useSelector(getUserEmailSelector);
  const [scheduleType, setScheduleType] = useState(props.scheduleType);
  const [scheduleDay, setScheduleDay] = useState(props.scheduleDay);
  const [scheduleTime, setScheduleTime] = useState(props.scheduleTime);
  const [recipients, setRecipients] = useState(props.recipients?.length ? props.recipients : [userEmail]);
  const [email, setEmail] = useState('');
  const [isEmailError, setIsEmailError] = useState(false);

  const timezone = useSelector(getUserTimezoneSelector);
  const dayList = scheduleType === RECURRENCE_VALUES.weekly.value ? DAY_OPTIONS_WEEKLY : DAY_OPTIONS;

  const setValuesFromProps = () => {
    setScheduleType(props.scheduleType);
    setScheduleDay(props.scheduleDay);
    setScheduleTime(props.scheduleTime);
    setRecipients(props.recipients?.length ? props.recipients : [userEmail]);
  };

  useEffect(() => {
    if (props.open) {
      setValuesFromProps();
    }
  }, [props.open]);

  const handleScheduleTypeChange = (value) => {
    setScheduleType(value);

    if (value === RECURRENCE_VALUES.daily.value) {
      setScheduleDay(null);
      setScheduleTime(TIME_OPTIONS[7].value);
    }

    if (value === RECURRENCE_VALUES.weekly.value) {
      setScheduleDay(DAY_OPTIONS_WEEKLY[0].value);
      setScheduleTime(TIME_OPTIONS[7].value);
    }

    if (value === RECURRENCE_VALUES.monthly.value) {
      setScheduleDay(DAY_OPTIONS[0].value);
      setScheduleTime(TIME_OPTIONS[7].value);
    }
  };

  const handleDeleteRecipient = (recepient) => {
    setRecipients(recipients.filter((item) => item !== recepient));
  };

  const handleClose = () => {
    props.onClose();
    setValuesFromProps();
  };

  const clearAll = () => {
    setScheduleType(null);
    setScheduleDay(null);
    setScheduleTime(null);
    setRecipients([]);
  };

  const handleSubmit = () => {
    props.setField({
      scheduleType,
      scheduleDay,
      scheduleTime,
      recipients,
    });
    props.onSubmit();
    props.onClose();
  };

  return (
    <Dialog open={props.open} onClose={handleClose} maxWidth="md">
      <DialogTitle onClose={handleClose}>
        {`Schedule ${props.name?.length ? `“${props.name}” ` : ''} delivery`}
      </DialogTitle>
      <DialogContent className={styles.Content}>
        <Typography variant="subtitle2" color="text.primary" fontWeight={400}>
          Please set the recepients and the schedule for this report.
        </Typography>

        <div className={styles.Filters}>
          <Autocomplete
            className={styles.Filter}
            data-id="recurrence"
            size="small"
            options={RECURRENCE_LIST}
            value={scheduleType}
            onChange={(event, newValue) => {
              handleScheduleTypeChange(newValue?.value ?? null);
            }}
            disabled={!recipients?.length}
            disableClearable
            renderInput={(params) => {
              const type = RECURRENCE_LIST.find((item) => item.value === scheduleType);
              // eslint-disable-next-line no-param-reassign
              params.inputProps.value = type?.label ?? '';
              return <TextField {...params} size="small" variant="outlined" label="Recurrence" placeholder="Select" />;
            }}
          />

          <Autocomplete
            className={styles.Filter}
            data-id="day"
            size="small"
            options={dayList}
            value={scheduleDay}
            onChange={(event, newValue) => {
              setScheduleDay(newValue?.value ?? null);
            }}
            disabled={!scheduleType || scheduleType === RECURRENCE_VALUES.daily.value || !recipients?.length}
            isOptionEqualToValue={(option, value) => option.value === value}
            disableClearable
            renderInput={(params) => {
              const day = dayList.find((item) => item.value === scheduleDay);
              // eslint-disable-next-line no-param-reassign
              params.inputProps.value = day?.label ?? '';

              return <TextField {...params} size="small" variant="outlined" label="Day" placeholder="Select" />;
            }}
          />

          <Autocomplete
            className={styles.Filter}
            data-id="time"
            size="small"
            options={TIME_OPTIONS}
            value={scheduleTime}
            onChange={(event, newValue) => {
              setScheduleTime(newValue?.value ?? null);
            }}
            disabled={!scheduleType || !recipients?.length}
            disableClearable
            renderInput={(params) => {
              const time = TIME_OPTIONS.find((item) => item.value === scheduleTime);
              // eslint-disable-next-line no-param-reassign
              params.inputProps.value = time?.label ?? '';

              return <TextField {...params} size="small" variant="outlined" label="Time" placeholder="Select" />;
            }}
          />
        </div>

        <TextField
          className={styles.Textfield}
          data-id="recipients"
          value={email}
          onChange={({ target }) => {
            setIsEmailError(false);
            setEmail(target.value);
          }}
          onKeyDown={({ keyCode, target }) => {
            const values = target.value?.trim()?.split(/(?:,|;| )+/);
            if (keyCode === KEY_ENTER) {
              if (values.every((item) => emailRegExp.test(item))) {
                setRecipients([...recipients, ...values]);
                setEmail('');
              } else {
                setIsEmailError(true);
              }
            }
          }}
          placeholder='Add up to 20 email addresses and press "Enter"'
          label="Add Recipients"
          variant="outlined"
          size="small"
          error={isEmailError}
        />

        <Typography className={styles.ChipsTitle} variant="body2" color="text.primary" fontWeight={400} component="div">
          Current recipients:
        </Typography>

        {!!recipients?.length && (
          <div className={styles.Chips}>
            {recipients.map((item, index) => (
              <Chip
                key={`${+index}-${item}`}
                className={styles.Chip}
                onDelete={() => {
                  handleDeleteRecipient(item);
                }}
                label={item}
                variant="filled"
                color="neutral"
                size="small"
                shape="circular"
              />
            ))}
          </div>
        )}

        <div className={styles.Hint}>
          <Typography
            className={styles.HintText}
            variant="caption"
            color="text.secondary"
            fontWeight={400}
            component="div"
          >
            {`Sending time is set in your current time zone ${timezone}`}
          </Typography>
          <Typography variant="caption" color="text.secondary" fontWeight={400} component="div">
            The report will be delivered as an email with a CSV file attached.
          </Typography>
          <Typography
            className={styles.HintText}
            variant="caption"
            color="text.secondary"
            fontWeight={400}
            component="div"
          >
            Files over 10MB will be compressed to ZIP.
          </Typography>
        </div>
      </DialogContent>
      <DialogActions>
        <Button className={styles.Actions} size="small" variant="text" color="primary" onClick={clearAll}>
          Clear All
        </Button>
        <Button variant="outlined" size="small" color="primary" onClick={handleClose}>
          Cancel
        </Button>
        <Button size="small" color="primary" onClick={handleSubmit}>
          Save Schedule
        </Button>
      </DialogActions>
    </Dialog>
  );
}

ScheduleDialog.propTypes = {
  open: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired,
  setField: PropTypes.func.isRequired,
  name: PropTypes.string.isRequired,
  scheduleType: PropTypes.string.isRequired,
  scheduleDay: PropTypes.number.isRequired,
  scheduleTime: PropTypes.number.isRequired,
  recipients: PropTypes.arrayOf(PropTypes.string).isRequired,
};

export default ScheduleDialog;
