import React, { useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { QSMRootState } from '../../store/qsm-store';
import { setFieldValue } from '../../store/qsm-slice';
import SearchInputGroup from '../search-input-group';
import { FieldConfig, DoubleFieldConfig } from '../../types';

const isDouble = (f: FieldConfig): f is DoubleFieldConfig => f.type === 'double';

interface Props {
  fieldConfig: DoubleFieldConfig;
  showReverse?: boolean;
}

const DoubleSearchInputGroup: React.FC<Props> = ({ fieldConfig, showReverse = false }) => {
  const dispatch = useDispatch();

  if (!fieldConfig || !isDouble(fieldConfig)) {
    return null;
  }

  const [firstCfg, secondCfg] = fieldConfig.fields;

  const firstSelector = useMemo(() => (s: QSMRootState) => (s.qsm as any)[firstCfg.fieldKey] ?? '', [firstCfg.fieldKey]);
  const secondSelector = useMemo(() => (s: QSMRootState) => (s.qsm as any)[secondCfg.fieldKey] ?? '', [secondCfg.fieldKey]);
  const firstValue = useSelector(firstSelector);
  const secondValue = useSelector(secondSelector);

  const reverse = () => {
    dispatch(
      setFieldValue({
        fieldKey: firstCfg.fieldKey,
        value: secondValue
      })
    );
    dispatch(
      setFieldValue({
        fieldKey: secondCfg.fieldKey,
        value: firstValue
      })
    );
  };

  return (
    <div className="qsm__double-input qsm__double-input--splittable">
      <div className="qsm__input-wrapper qsm__input-wrapper--splittable">
        <SearchInputGroup fieldConfig={firstCfg} isDoubleInput />
      </div>

      {showReverse ? (
        <div className="qsm__reverse-wrapper">
          <button type="button" onClick={reverse} className="qsm__input-line--reverse-button" tabIndex={-1}>
            <svg id="qsm-planes-icon" viewBox="0 0 18 18" width={18} height={18}>
              <path
                d="M98.994-878.02l1.642-3.992H98.578l-1.081,1.5H96l1-2.744L96-886h1.5l1.081,1.5h1.85L98.994-888h1.5l2.6,3.493h3.139a1.2,1.2,0,0,1,.884.364,1.2,1.2,0,0,1,.364.884,1.2,1.2,0,0,1-.364.884,1.2,1.2,0,0,1-.884.364h-2.765l-2.973,3.992Zm7.984,6.986-2.245-3.493h-2.994a1.2,1.2,0,0,1-.884-.364,1.2,1.2,0,0,1-.364-.884,1.2,1.2,0,0,1,.364-.884,1.2,1.2,0,0,1,.884-.364H104.4l2.578-3.992h1.5l-1.247,3.992h2.162l1.081-1.5h1.5l-1,2.744,1,2.744h-1.5l-1.081-1.5h-2l1.081,3.493Z"
                transform="translate(-95 889)"
              />
            </svg>
          </button>
        </div>
      ) : (
        <div className="qsm__input-line qsm__input-line--splittable" />
      )}

      <div className="qsm__input-wrapper qsm__input-wrapper--splittable">
        <SearchInputGroup
          fieldConfig={secondCfg}
          isSecondInput
          isDoubleInput
          isDisabled={fieldConfig.disableReturnField}
          readOnlyForced={fieldConfig.disableReturnField}
        />
      </div>
    </div>
  );
};

export default DoubleSearchInputGroup;
