import React, { useState, useEffect } from 'react';
import { faClock } from '@fortawesome/free-solid-svg-icons/faClock';
import { Checkbox } from '../checkbox';
import { DropdownMenu } from '../dropdown-menu';
import { Input } from '../input';
import { FREQUENCIES, DEFAULT_SCHEDULES } from './constants';
import { getFrequency, stringToArrayOfNumbersOrAll } from './utils';
import { MESSAGE_TYPES } from '../message';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const isInteger = /^\d+$/;
function MinutePicker({
  minute,
  onUpdateMinute,
  label,
  validationErrorText,
  isDisabled
}) {
  const [inputValue, setInputValue] = useState(minute?.[0]);
  const [validityError, setValidityError] = useState();
  useEffect(function () {
    if (!validityError) {
      onUpdateMinute({
        minute: [Number(inputValue)]
      });
    } else {
      onUpdateMinute({
        minute
      }, validityError);
    }
  }, [inputValue]);
  function handleUpdate(e) {
    const {
      value
    } = e.target;
    const parsedValue = parseInt(value);
    const isValid = isInteger.test(value) && parsedValue >= 0 && parsedValue <= 59;
    setValidityError(isValid ? undefined : {
      type: MESSAGE_TYPES.ERROR,
      value: validationErrorText,
      field: 'minute'
    });
    setInputValue(value);
  }
  return /*#__PURE__*/_jsx(Input, {
    type: "number",
    min: 0,
    max: 59,
    step: 1,
    value: inputValue,
    label: label,
    "test-id": "minute-picker",
    id: "minutes-input",
    validity: validityError,
    onChange: handleUpdate,
    isDisabled: isDisabled
  });
}
function TimePicker({
  hour,
  minute,
  onUpdateTime,
  label,
  validationErrorText,
  isDisabled
}) {
  const paddedHour = hour?.toString().padStart(2, '0');
  const paddedMinute = minute?.toString().padStart(2, '0');
  const [inputValue, setInputValue] = useState({
    hour: paddedHour,
    minute: paddedMinute
  });
  const [validityError, setValidityError] = useState();
  useEffect(() => {
    onUpdateTime({
      hour: [Number(inputValue.hour)],
      minute: [Number(inputValue.minute)]
    }, validityError);
  }, [inputValue]);
  function handleChange(e) {
    const {
      value
    } = e.target;
    const splitTime = value.split(':');
    const hourString = splitTime[0] || '';
    const minuteString = splitTime[1] || '';
    const isValid = isInteger.test(hourString) && isInteger.test(minuteString);
    setValidityError(isValid ? undefined : {
      type: MESSAGE_TYPES.ERROR,
      value: validationErrorText,
      field: 'time'
    });
    setInputValue({
      hour: hourString,
      minute: minuteString
    });
  }
  return /*#__PURE__*/_jsx(Input, {
    label: label,
    type: "time",
    "test-id": "time-picker",
    id: "time-input",
    value: `${inputValue.hour}:${inputValue.minute}`,
    validity: validityError,
    onChange: handleChange,
    step: 60,
    rightIcon: faClock,
    isDisabled: isDisabled
  });
}
const DayOfWeekPicker = ({
  dayOfWeek = [],
  onUpdateDayOfWeek,
  daysOfWeek,
  label,
  isDisabled
}) => {
  const selectedDayOfWeek = dayOfWeek?.map(i => i) ?? [];
  return /*#__PURE__*/_jsxs("div", {
    className: "day-of-week-picker",
    "test-id": "day-of-week-picker",
    children: [/*#__PURE__*/_jsx("span", {
      className: "day-of-week-label",
      children: label
    }), daysOfWeek.map(day => /*#__PURE__*/_jsx("span", {
      children: /*#__PURE__*/_jsx(Checkbox, {
        id: `day-of-week-${day.index}`,
        testId: `day-of-week-checkbox-${day.index}`,
        className: "scheduler-checkbox",
        isChecked: selectedDayOfWeek.includes(day.index),
        labelText: day.label,
        onChange: e => {
          onUpdateDayOfWeek({
            dayOfWeek: e.target.checked ? [...dayOfWeek, day.index] : dayOfWeek?.filter(item => item !== day.index)
          });
        },
        isDisabled: isDisabled
      })
    }, `day-of-week-checkbox-${day.index}`))]
  });
};
const MonthPicker = ({
  month,
  onUpdateMonth,
  months,
  label,
  isDisabled
}) => /*#__PURE__*/_jsxs("div", {
  className: "month-picker",
  "test-id": "month-picker",
  children: [/*#__PURE__*/_jsx("span", {
    className: "month-checkbox-label",
    children: label
  }), Object.values(months).map(item => /*#__PURE__*/_jsx("span", {
    children: /*#__PURE__*/_jsx(Checkbox, {
      id: `month-${item.index}`,
      testId: `month-checkbox-${item.index}`,
      className: "scheduler-checkbox",
      isChecked: month.includes(item.index),
      labelText: item.label,
      onChange: e => {
        onUpdateMonth({
          month: e.target.checked ?
          // Need to refactor the whole components to get ride of these 'as's
          [...month, item.index] : month.filter(m => m !== item.index)
        });
      },
      isDisabled: isDisabled
    })
  }, `month-checkbox-${item.index}`))]
});
function DayOfMonthPicker({
  dayOfMonth,
  onUpdateDayOfMonth,
  validateArrayOfRangedNumbersOrAll,
  label,
  isDisabled
}) {
  const [inputValue, setInputValue] = useState(dayOfMonth?.join(','));
  const [validityError, setValidityError] = useState();
  useEffect(function () {
    if (!validityError) {
      onUpdateDayOfMonth({
        dayOfMonth: stringToArrayOfNumbersOrAll(inputValue)
      });
    } else {
      onUpdateDayOfMonth({
        dayOfMonth: stringToArrayOfNumbersOrAll(validityError?.validValues)
      }, validityError);
    }
  }, [inputValue]);
  function handleUpdate(value) {
    const values = value.split(',').filter(day => day);
    const updateValidity = validateArrayOfRangedNumbersOrAll({
      values,
      min: 1,
      max: 31,
      allowAll: false
    });
    setValidityError(updateValidity ? {
      ...updateValidity,
      field: 'dayOfMonth'
    } : undefined);
    setInputValue(value);
  }
  return /*#__PURE__*/_jsx("div", {
    "test-id": "day-of-month-picker",
    children: /*#__PURE__*/_jsx(Input, {
      id: "dayOfMonth",
      "test-id": "day-of-month-input",
      label: label,
      name: "dayOfMonth",
      onChange: e => handleUpdate(e.target.value),
      value: inputValue,
      validity: validityError
      // show validity errors as they are typed without having to wait for the first blur
      ,
      touched: true,
      isDisabled: isDisabled
    })
  });
}
export function SimpleScheduler({
  onUpdateSchedule,
  initialSchedule,
  frequencyOptions,
  validateArrayOfRangedNumbersOrAll,
  daysOfWeek,
  months,
  labelTexts,
  validationTexts,
  isDisabled
}) {
  const [schedule, setSchedule] = useState(initialSchedule);
  const [frequency, setFrequency] = useState(getFrequency(initialSchedule));

  // TODO: Refactor with generic DropdownMenu
  function handleSelectFrequency(option) {
    setFrequency(option?.key);
    setSchedule(DEFAULT_SCHEDULES[option?.key]);
    onUpdateSchedule({
      newSchedule: DEFAULT_SCHEDULES[option?.key],
      errors: null
    });
  }
  function handleUpdateSchedule({
    minute,
    hour,
    dayOfMonth,
    month,
    dayOfWeek
  }, error = null) {
    const newSchedule = {
      minute: minute || schedule.minute,
      hour: hour || schedule.hour,
      dayOfMonth: dayOfMonth || schedule.dayOfMonth || error?.validValues,
      month: month || schedule.month,
      dayOfWeek: dayOfWeek || schedule.dayOfWeek
    };
    const errors = error ? [error] : null;
    setSchedule(newSchedule);
    onUpdateSchedule({
      newSchedule,
      errors
    });
  }
  return /*#__PURE__*/_jsxs("div", {
    className: "simple-scheduler-form",
    "test-id": "simple-scheduler",
    children: [/*#__PURE__*/_jsx(DropdownMenu, {
      labelText: labelTexts.frequency,
      options: frequencyOptions,
      selectedKey: frequency,
      placement: "bottom",
      onSelect: handleSelectFrequency,
      selectbox: true,
      triggerTestId: "frequency-picker-trigger",
      triggerAriaLabelText: labelTexts.frequency,
      contentTestId: "frequency-picker-content",
      isDisabled: isDisabled
    }), frequency === FREQUENCIES.HOURLY && /*#__PURE__*/_jsx(MinutePicker, {
      minute: schedule.minute,
      onUpdateMinute: handleUpdateSchedule,
      label: labelTexts.minutesPastHour,
      validationErrorText: validationTexts.minuteError,
      isDisabled: isDisabled
    }, `minute-${frequency}`), (frequency === FREQUENCIES.DAILY || frequency === FREQUENCIES.WEEKLY || frequency === FREQUENCIES.MONTHLY || frequency === FREQUENCIES.QUARTERLY || frequency === FREQUENCIES.YEARLY) && /*#__PURE__*/_jsx(TimePicker, {
      hour: schedule?.hour?.[0],
      minute: schedule?.minute?.[0],
      onUpdateTime: ({
        minute,
        hour
      }, validityError) => {
        handleUpdateSchedule({
          minute,
          hour
        }, validityError);
      },
      label: labelTexts.time,
      validationErrorText: validationTexts.timeError,
      isDisabled: isDisabled
    }, `time-${frequency}`), frequency === FREQUENCIES.WEEKLY && /*#__PURE__*/_jsx(DayOfWeekPicker, {
      dayOfWeek: schedule.dayOfWeek,
      onUpdateDayOfWeek: ({
        dayOfWeek
      }) => {
        handleUpdateSchedule({
          dayOfWeek
        });
      },
      daysOfWeek: daysOfWeek,
      label: labelTexts.days,
      isDisabled: isDisabled
    }, `day-of-week-${frequency}`), (frequency === FREQUENCIES.MONTHLY || frequency === FREQUENCIES.QUARTERLY || frequency === FREQUENCIES.YEARLY) && /*#__PURE__*/_jsx(DayOfMonthPicker, {
      dayOfMonth: schedule.dayOfMonth,
      onUpdateDayOfMonth: handleUpdateSchedule,
      validateArrayOfRangedNumbersOrAll: validateArrayOfRangedNumbersOrAll,
      label: labelTexts.dayOfMonth,
      isDisabled: isDisabled
    }, `day-of-month-${frequency}`), frequency === FREQUENCIES.YEARLY && /*#__PURE__*/_jsx(MonthPicker, {
      month: schedule.month,
      onUpdateMonth: handleUpdateSchedule,
      months: months,
      label: labelTexts.months,
      isDisabled: isDisabled
    }, `month-${frequency}`)]
  });
}