import '@jswork/next-tree-walk';
import { TreeSelect, TreeSelectProps } from 'antd';
import cx from 'classnames';
import React from 'react';
import { treeSelectKv } from '../tpls/kv';
import type { StdCallback } from './types';

const CLASS_NAME = 'ac-tree-select';

// @see: https://github.com/afeiship/react-ant-tree-select

export type AcTreeSelectProps = {
  className?: string;
  items?: any[];
  template?: any;
  itemsKey?: string | ((index: number, item: any) => any);
  onChange?: StdCallback;
} & TreeSelectProps;

export class AcTreeSelect extends React.Component<AcTreeSelectProps> {
  static displayName = CLASS_NAME;
  static formSchema = CLASS_NAME;
  static defaultProps = {
    items: [],
    template: treeSelectKv,
    itemsKey: 'children',
  };

  get childView() {
    const { items, template, itemsKey } = this.props;
    return nx.treeWalk(items!, { template, itemsKey });
  }

  handleChange = (inValue) => {
    const { onChange } = this.props;
    onChange?.({ target: { value: inValue } });
  };

  render() {
    const { className, items, itemsKey, template, treeData, onChange, ...props } = this.props;

    return (
      <TreeSelect
        data-component={CLASS_NAME}
        className={cx(CLASS_NAME, className)}
        onChange={this.handleChange}
        treeNodeFilterProp="title"
        {...props}>
        {this.childView}
      </TreeSelect>
    );
  }
}

export const AcTreeSelectFc = (props: AcTreeSelectProps) => {
  return <AcTreeSelect {...props} />;
};
