import React from 'react';

import type { MetadataFeedTimezoneType } from '@/modules/feeds/Editor/types';
import type { GeneralSizeProp } from '@/mui/types';

import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import {
  defaultTimezoneSelector,
  metadataTimezonesSelector,
  schemeSelector,
} from '@/modules/feeds/Editor/redux/selectors';
import { removeErrorByPropAction, setAction } from '@/modules/feeds/Editor/redux/slices';

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

type PropTypes = {
  disabled?: boolean;
};

function TimezoneSelect({ disabled = false }: PropTypes) {
  const dispatch = useAppDispatch();
  const { size } = useFormSettings();

  const scheme = useAppSelector(schemeSelector);
  const defaultTimezone = useAppSelector(defaultTimezoneSelector);
  const options = useAppSelector(metadataTimezonesSelector);
  const value = options?.find((timezone) => timezone.value === defaultTimezone);

  return (
    <Autocomplete
      value={value}
      options={options || []}
      loading={!options}
      size={size as GeneralSizeProp}
      optionLabelKey="name"
      optionValueKey="value"
      disabled={disabled}
      onChange={(_, selected$) =>
        dispatch(
          setAction({
            defaultTimezone: (selected$ as MetadataFeedTimezoneType)?.value,
          }),
        )
      }
      renderInput={(params) => (
        <TextField
          {...params}
          value=""
          variant="outlined"
          placeholder="Select Timezone"
          {...getInputPropsByName(scheme, ['defaultTimezone'])}
          label=""
          onFocus={() => dispatch(removeErrorByPropAction(['defaultTimezone']))}
        />
      )}
    />
  );
}

export default TimezoneSelect;
