import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';

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

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

function GeneralTab() {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const router = useRouter();

  // selectors
  const name = useSelector(selectors.nameSelector);
  const account = useSelector(selectors.accountSelector);
  const accountOptions = useSelector(selectors.accountOptionsSelector);
  const scheme = useSelector(selectors.schemeSelector);

  const id = parseInt(router.query.id, 10);

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

  return (
    <>
      <FormRow label="Advertiser Name">
        <TextField
          size={size}
          placeholder="Enter Advertiser Name"
          value={name}
          onChange={(e) => handleSetState({ name: e.target.value })}
          {...getInputPropsByName(scheme, ['name'])}
          onFocus={() => dispatch(removeErrorByPropAction(['name']))}
        />
      </FormRow>
      <FormRow label="Demand account">
        <Autocomplete
          size={size}
          options={accountOptions || []}
          value={account}
          optionLabelKey="name"
          optionValueKey="id"
          disabled={id}
          renderInput={(params) => (
            <TextField
              {...params}
              value=""
              placeholder="Select Account"
              {...getInputPropsByName(scheme, ['account'])}
              onFocus={() => dispatch(removeErrorByPropAction(['account']))}
            />
          )}
          filterSelectedOptions
          onOpen={() => dispatch(getAccountOptionsAction())}
          onChange={(e, account$) =>
            handleSetState({
              account: account$,
            })
          }
        />
      </FormRow>
    </>
  );
}

export default GeneralTab;
