/* eslint-disable max-len */
import * as React from 'react';
import { useEffect } from 'react';
import { FastTreeSelect } from 'components/ui';
import { Component } from 'components/types';
import useOptions from '../hooks/useOptions';
import { FormTypes } from '../../types';

const STRATEGY_MAP = {
  all: FastTreeSelect.SHOW_ALL,
  parent: FastTreeSelect.SHOW_PARENT,
  child: FastTreeSelect.SHOW_CHILD,
};

function TreeSelect(props: FormTypes.FormItem.FormAtomicSelectProps) {
  const { config, values, validateTrigger } = props;
  const {
    type,
    key,
    style,
    placeholder,
    notModify,
    searchable = false,
    data: defaultOptions,
    interact,
    dataLabel,
    showCheckedStrategy = FormTypes.FormItem.CheckedStrategy.all,
  } = config;

  // states
  const { ajaxOptions, setOptions } = useOptions(props);

  // handlers
  const handleSearch = (value: string) => {
    if (searchable) {
      setOptions({ [key]: value });
    }
  };

  // effects
  useEffect(setOptions, [setOptions]);

  // effects
  const deps = interact && [
    Component.Business.ResultType.fetch,
    Component.Business.ResultType.show,
  ].includes(interact.type)
    ? [values[interact.triggerKey as string]] : [];

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(
    setOptions,
    [
      // setOptions,
      ...deps,
    ],
  );
  return (
    <FastTreeSelect
      style={{ ...style, minWidth: '150px' }}
      value={values[key]}
      placeholder={placeholder}
      // eslint-disable-next-line no-nested-ternary
      treeData={ajaxOptions && ajaxOptions.length > 0
        ? defaultOptions && defaultOptions.length
          ? [...defaultOptions, ...ajaxOptions]
          : ajaxOptions
        : defaultOptions}
      onSearch={handleSearch}
      treeNodeFilterProp={dataLabel}
      showSearch
      multiple={type === 'multtreeselect'}
      showCheckedStrategy={STRATEGY_MAP[showCheckedStrategy]}
      disabled={notModify}
      // eslint-disable-next-line react/destructuring-assignment
      onChange={props[validateTrigger]}
      treeDefaultExpandAll
    />
  );
}

export default TreeSelect;
