import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

import * as selectors from '../../../redux/selectors';
import { getDemandAccountsOptionsAction, removeErrorByPropAction, setAction } from '../../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';

import { FormRow, useFormSettings } from '@/modules/@common/Form';
import { Autocomplete, Switch, TextField } from '@/mui/components';

function MarketplaceSelfServiceTab() {
  const { size } = useFormSettings();
  const dispatch = useDispatch();

  const scheme = useSelector(selectors.schemeSelector);
  const mpSelfService = useSelector(selectors.mpSelfServiceSelector);
  const demandAccount = useSelector(selectors.demandAccountSelector);
  const demandAccountsOptions = useSelector(selectors.demandAccountsOptionsSelector);

  const handleSetState = (state) => dispatch(setAction(state));

  return (
    <>
      <FormRow label="MP Self Service">
        <Switch
          color="primary"
          size={size}
          checked={mpSelfService}
          onChange={({ target }) => {
            handleSetState({
              mpSelfService: target.checked,
              ...(!target.checked && {
                demandAccount: null,
                demandAccountId: null,
              }),
            });
          }}
        />
      </FormRow>
      {mpSelfService && (
        <FormRow label="Demand Account">
          <Autocomplete
            size={size}
            loading={!demandAccountsOptions}
            options={demandAccountsOptions || []}
            value={demandAccount}
            disabled={!mpSelfService}
            optionLabelKey="name"
            optionValueKey="id"
            onOpen={() =>
              dispatch(
                getDemandAccountsOptionsAction({
                  searchText: '',
                }),
              )
            }
            onChange={(_, selected) =>
              handleSetState({
                demandAccount: selected,
                demandAccountId: selected?.id ?? null,
              })
            }
            onInputChange={(_, searchText) => {
              dispatch(
                getDemandAccountsOptionsAction({
                  searchText,
                }),
              );
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                placeholder="Select Account"
                {...getInputPropsByName(scheme, ['demandAccount'])}
                onFocus={() => dispatch(removeErrorByPropAction(['demandAccount']))}
              />
            )}
          />
        </FormRow>
      )}
    </>
  );
}

export default MarketplaceSelfServiceTab;
