import React from 'react';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';

import { DateTimePicker, Stack } from '@/mui/components';

const fromTo = {
  from: 'from',
  to: 'to',
};

function FilterDatePicker({ size = 'medium', ...props }) {
  const { from, to } = props.selected[0];
  const handleOnChange = (type, fieldValue) =>
    props.selectAction({
      ...props.config,
      value: [
        {
          ...props.selected[0],
          [type]: fieldValue,
        },
      ],
    });

  return (
    <Stack spacing={2} fullWidth direction="row" alignItems="center">
      <DateTimePicker
        clearable
        value={from ? dayjs(from) : undefined}
        label="From"
        data-id="filterDatePickerStartTime"
        maxDate={to ? dayjs(to) : undefined}
        maxDateMessage="Date should not be after end date"
        slotProps={{
          textField: {
            size,
            placeholder: 'mm/dd/yyyy hh:mm',
          },
        }}
        onChange={(date) => handleOnChange(fromTo.from, date?.toDate().getTime())}
      />
      <DateTimePicker
        clearable
        value={to ? dayjs(to) : undefined}
        label="To"
        data-id="filterDatePickerEndTime"
        minDate={from ? dayjs(from) : undefined}
        minDateMessage="Date should not be before start date"
        slotProps={{
          textField: {
            placeholder: 'mm/dd/yyyy hh:mm',
            size: 'small',
          },
        }}
        onChange={(date) => handleOnChange(fromTo.to, date?.toDate().getTime())}
      />
    </Stack>
  );
}

FilterDatePicker.propTypes = {
  selected: PropTypes.arrayOf(
    PropTypes.shape({
      from: PropTypes.string,
      to: PropTypes.string,
    }),
  ).isRequired,
  config: PropTypes.shape({}).isRequired,
  selectAction: PropTypes.func.isRequired,
  size: PropTypes.oneOf(['xSmall', 'small', 'medium', 'large']),
};

export default FilterDatePicker;
