import React from 'react';

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

import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import { accountOptionsSelector, accountSelector, schemeSelector } from '@/modules/feeds/Editor/redux/selectors';
import { getAccountOptionsAction, 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 Account({ disabled = false }: PropTypes) {
  const dispatch = useAppDispatch();
  const { size } = useFormSettings();

  const scheme = useAppSelector(schemeSelector);
  const account = useAppSelector(accountSelector);
  const accountOptions = useAppSelector(accountOptionsSelector);

  return (
    <Autocomplete
      value={account}
      options={accountOptions || []}
      loading={!accountOptions}
      size={size as GeneralSizeProp}
      optionLabelKey="name"
      optionValueKey="id"
      disabled={disabled}
      onChange={(_, selected$) =>
        dispatch(
          setAction({
            account: selected$ as FeedType['account'],
          }),
        )
      }
      onOpen={() => dispatch(getAccountOptionsAction({ searchText: '' }))}
      onInputChange={(e, searchAccountText) => dispatch(getAccountOptionsAction({ searchText: searchAccountText }))}
      renderInput={(params) => (
        <TextField
          {...params}
          value=""
          variant="outlined"
          placeholder="Select Account"
          {...getInputPropsByName(scheme, ['account'])}
          onFocus={() => dispatch(removeErrorByPropAction(['account']))}
        />
      )}
    />
  );
}

export default Account;
