import React, { Component, Ref } from "react";

import Modal, { ModalProps } from "../../Common/Modal";
import WantedPublishView from "../WantedPublishView";
import styles from "./WantedPublishModal.less";
import {
  WatnedPublishBase,
  WatnedPublishBaseP
} from "@components/Payment/BaseClassComponents/WantedPublish";

interface WantedPublishModalProps extends WatnedPublishBaseP {
  modalConfig?: ModalProps;
}

interface WantedPublishModalState {
  modalVisible: boolean;
  current_wanted: number | string | null;
}

export class WantedPublishModal extends WatnedPublishBase<
  WantedPublishModalProps,
  WantedPublishModalState
> {
  constructor(props: WantedPublishModalProps) {
    super(props);
    this.state = {
      modalVisible: false,
      current_wanted: null
    };
  }

  handleConfirmButton = (containerRef?: React.RefObject<any>) => {
    const { handleConfirm } = this.props;
    if (handleConfirm) {
      const value = this.formatCurrentWanted(this.state.current_wanted);
      handleConfirm(value ? Number(value).toFixed(2) : value);
    }
    this.setState({ modalVisible: false });
  };

  renderMain() {
    const { current_wanted } = this.state;
    return (
      <WantedPublishView
        wrapperClass={styles.modalBg}
        current_wanted={current_wanted}
        InputWantedValueChange={(v: string) =>
          this.setState({ current_wanted: v })
        }
        InputWantedPressEnter={(v: string) => {
          const value = this.formatCurrentWanted(v);
          if (this.props.handleConfirm)
            this.props.handleConfirm(this.formatResult(value));
          this.setState({ current_wanted: value, modalVisible: false });
        }}
        InputWantedOnBlur={(v: string) => {
          const value = this.formatCurrentWanted(v);
          this.setState({ current_wanted: value });
        }}
        InputWantedClear={() => {
          this.setState(
            {
              current_wanted: null
            },
            () => {
              if (this.props.handleConfirm) this.props.handleConfirm(null);
              this.setState({ modalVisible: false });
            }
          );
        }}
        InputWantedConfirm={this.handleConfirmButton}
        {...this.props.viewConfig}
      />
    );
  }

  render() {
    return (
      <>
        <div onClick={() => this.setState({ modalVisible: true })}>
          {this.props.children}
        </div>
        <Modal
          visible={this.state.modalVisible}
          onCancel={() => {
            this.setState({ modalVisible: false });
          }}
          {...this.props.modalConfig}
        >
          {this.renderMain()}
        </Modal>
      </>
    );
  }
}

export default WantedPublishModal;
