import React, { CSSProperties } from 'react';
import {FormItem, FormControlProps, FormBaseControl} from './Item';
import cx from 'classnames';
// import LazyComponent from '../../components/LazyComponent';
import Milkdown from '../../components/milkdown'

/**
 * Milkdown
 */
 export interface MilkdownlSchema extends FormBaseControl {
  type: 'input-md'
  value: string
  options?: any;
}


export interface MilkdownProps extends FormControlProps {
  options?: any;
  height?: number
  autoSize?: boolean
  onBlur: (ctx: any) => void
  onFocus: (ctx: any) => void
}

// function loadMilkdown(): () => Promise<any> {
//   return () => import(/* webpackChunkName: "milkdown" */'../../components/milkdown').then(item => item.default)
// }

export default class MilkdownControl extends React.Component<
  MilkdownProps,
  any
> {
  static defaultProps: Partial<MilkdownProps> = {
    value: '',
    autoSize: true,// 是否能自动变高
    height: 178,// 默认高度
    options: {
    }
  };

  state = {
    focused: false
  };
  config: any = null;
  constructor(props: MilkdownProps) {
    super(props);

    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
    this.handleChange = this.handleChange.bind(this);

  }

  handleFocus(ctx: any) {
    const {onFocus, disabled} = this.props;

    if (disabled) {
      return;
    }

    onFocus?.(ctx);

    this.setState({
      focused: true
    });
  }

  handleBlur(ctx: any) {
    const {onBlur, disabled} = this.props;

    if (disabled) {
      return;
    }

    onBlur?.(ctx);

    this.setState({
      focused: false
    });
  }

  handleChange(
    value: any,
  ) {
    const {onChange, disabled} = this.props;

    if (disabled) {
      return;
    }

    onChange?.(value);
  }

  render() {
    const {
      className,
      classPrefix: ns,
      value,
      disabled,
      locale,
      height,
      autoSize,
      translate
    } = this.props;

    const style: CSSProperties = {}
    if(height){
      style[autoSize? 'minHeight': 'height'] = height
    }

    let model = value || '';
    if(model){
      model = model.replace(/<\/?[^>]+>/g,"");
    }
    return (
      <div
        className={cx(`${ns}MilkdownControl`, className, {
          'is-focused': this.state.focused,
          'is-disabled': disabled
        })}
        style={style}
      >
        <Milkdown
          // getComponent={loadMilkdown()}
          model={model}
          onModelChange={this.handleChange}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
          // focused={this.state.focused}
          config={this.config}
          disabled={disabled}
          locale={locale}
          translate={translate}
        />
      </div>
    );
  }
}

@FormItem({
  type: 'input-md',
  sizeMutable: false
})
export class MilkdownRenderer extends MilkdownControl {}
