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

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

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

import styles from './GeneralTab.module.scss';

const NAME_MAX_LENGTH = 40;
const ADVERTISER_MAX_LENGTH = 40;

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

  const [advertiserSearchText, setAdvertiserSearchText] = useState('');

  // selectors
  const name = useSelector(selectors.nameSelector);
  const advertiser = useSelector(selectors.advertiserSelector);
  const advertiserOptions = useSelector(selectors.advertiserOptionsSelector);
  const hub = useSelector(selectors.hubSelector);
  const hubOptions = useSelector(selectors.hubOptionsSelector);

  const scheme = useSelector(selectors.schemeSelector);

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

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

  return (
    <>
      <FormRow label="Hub">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={hub}
            options={hubOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!hubOptions}
            size={size}
            filterSelectedOptions
            disableClearable
            disabled={!!id}
            onChange={(e, selected) => {
              handleSetState({
                hub: selected,
              });
            }}
            onOpen={() => {
              dispatch(getHubOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getHubOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Hub"
                {...getInputPropsByName(scheme, ['hub'])}
                onFocus={() => dispatch(removeErrorByPropAction(['hub']))}
              />
            )}
          />
        </Stack>
      </FormRow>

      <FormRow label="Name">
        <TextField
          size={size}
          placeholder="Name"
          value={name}
          inputProps={{ maxLength: NAME_MAX_LENGTH }}
          onChange={(e) => handleSetState({ name: e.target.value })}
          {...getInputPropsByName(scheme, ['name'])}
          onFocus={() => dispatch(removeErrorByPropAction(['name']))}
        />
      </FormRow>

      <FormRow label="Advertising Brand">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={advertiser}
            inputValue={advertiserSearchText}
            options={advertiserOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!advertiserOptions}
            size={size}
            filterSelectedOptions
            disableClearable
            onChange={(e, selected) => {
              handleSetState({
                advertiser: selected,
              });
            }}
            onOpen={() => {
              dispatch(getAdvertiserOptionsAction(''));
            }}
            onInputChange={(e, searchText) => {
              setAdvertiserSearchText(searchText);
              dispatch(getAdvertiserOptionsAction(searchText));
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Advertising Brand"
                inputProps={{ ...params.inputProps, maxLength: ADVERTISER_MAX_LENGTH }}
                {...getInputPropsByName(scheme, ['advertiser'])}
                onFocus={() => dispatch(removeErrorByPropAction(['advertiser']))}
              />
            )}
            PaperComponent={({ children }) => (
              <Paper className={styles.AddPaper}>
                {!!advertiserSearchText &&
                  advertiserOptions &&
                  !advertiserOptions?.some((d) => d.name === advertiserSearchText) && (
                    <div className={styles.AddPaperButtonWrapper}>
                      <Button
                        size="small"
                        color="primary"
                        variant="contained"
                        fullWidth
                        multiline
                        onMouseDown={() => {
                          dispatch(createAdvertiserAction(advertiserSearchText));
                        }}
                      >
                        {`Add Advertising Brand: ${advertiserSearchText}`}
                      </Button>
                    </div>
                  )}
                {children}
              </Paper>
            )}
          />
        </Stack>
      </FormRow>
    </>
  );
}

export default GeneralTab;
