import React from 'react';
import dayjs from 'dayjs';

import type { GeneralSizeProp } from '@/mui/types';

import { scheduleValueSelector } from '@/modules/feeds/Editor/redux/selectors';
import { setAction } from '@/modules/feeds/Editor/redux/slices';

import { useFormSettings } from '@/modules/@common/Form';
import { useAppDispatch, useAppSelector } from '@/modules/@common/store/hooks';
import { Stack, TimePicker } from '@/mui/components';

type PropTypes = {
  disabled?: boolean;
};

function ScheduleStartTime({ disabled = false }: PropTypes) {
  const dispatch = useAppDispatch();
  const settings = useFormSettings();
  const size = settings.size as GeneralSizeProp;

  const scheduleValue = useAppSelector(scheduleValueSelector);

  return (
    <Stack fullWidth>
      <TimePicker
        slotProps={{
          textField: {
            size,
          },
        }}
        value={dayjs(scheduleValue, 'HH:mm')}
        onChange={(triggerTime) => {
          const isValid = dayjs(triggerTime).isValid();
          const value = dayjs(triggerTime).format('HH:mm');
          dispatch(
            setAction({
              scheduleValue: isValid ? value : '00:00',
            }),
          );
        }}
        ampm={false}
        views={['hours', 'minutes']}
        format="HH:mm"
        disabled={disabled}
      />
    </Stack>
  );
}

export default ScheduleStartTime;
