import React from 'react';

import { ALL_HUB_OPTION, ALL_OPTION_ID } from '@/modules/feeds/Editor/constants';

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

import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import {
  accessAllPublishersSelector,
  accessPublishersSelector,
  hubsOptionsSelector,
  schemeSelector,
} from '@/modules/feeds/Editor/redux/selectors';
import { getHubsOptionsAction, 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;
};

type HubType = {
  id: number;
  name: string;
};

export const addAllHubsOption = (options: HubType[]): HubType[] => [ALL_HUB_OPTION, ...options];

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

  const scheme = useAppSelector(schemeSelector);
  const accessAllPublishers = useAppSelector(accessAllPublishersSelector);
  const accessPublishers = useAppSelector(accessPublishersSelector);
  const hubsOptions = useAppSelector(hubsOptionsSelector);

  const hubs = accessAllPublishers ? [ALL_HUB_OPTION] : accessPublishers;

  return (
    <Autocomplete
      fullWidth
      multiple
      value={hubs}
      options={hubsOptions?.length ? addAllHubsOption(hubsOptions) : []}
      loading={!hubsOptions}
      size={size as GeneralSizeProp}
      optionLabelKey="name"
      optionValueKey="id"
      disabled={disabled}
      filterSelectedOptions
      disableClearable
      filterOptions={(options) => {
        const hasAllOption = accessPublishers.some((option) => option.id === ALL_OPTION_ID);
        return hasAllOption ? [] : options;
      }}
      onChange={(e, selected) => {
        const selected$ = selected as FeedType['accessPublishers'];
        const hasAllOption = selected$.some((option) => option.id === ALL_OPTION_ID);
        dispatch(
          setAction({
            accessAllPublishers: hasAllOption,
            accessPublishers: hasAllOption ? [ALL_HUB_OPTION] : selected$,
          }),
        );
      }}
      onOpen={() => dispatch(getHubsOptionsAction({ searchText: '' }))}
      onInputChange={(e, searchAccountText) => dispatch(getHubsOptionsAction({ searchText: searchAccountText }))}
      renderInput={(params) => (
        <TextField
          {...params}
          value=""
          variant="outlined"
          placeholder="Select Hubs"
          {...getInputPropsByName(scheme, ['accessPublishers'])}
          onFocus={() => dispatch(removeErrorByPropAction(['accessPublishers']))}
        />
      )}
    />
  );
}

export default Account;
