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 {
  accessVideoOwnerSelector,
  ownersOptionsSelector,
  schemeSelector,
} from '@/modules/feeds/Editor/redux/selectors';
import { getOwnersOptionsAction, 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 AccessVideoOwner({ disabled = false }: PropTypes) {
  const dispatch = useAppDispatch();
  const { size } = useFormSettings();

  const scheme = useAppSelector(schemeSelector);
  const accessVideoOwner = useAppSelector(accessVideoOwnerSelector);
  const ownersOptions = useAppSelector(ownersOptionsSelector);

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

export default AccessVideoOwner;
