import { Component } from 'preact';

import PopupContainer from '../popup-container/popup-container';

import * as styles from './css/index.less';

interface ActInputQQProps {
  show?: boolean;
  title?: string;
  qqNumber?: string;
  onClickButton?: (qqNumber: string) => void;
  closeDialog?: () => void;
  onClickCancel?: () => void;
  onQQNumberChange?: (qqNumber: string) => void;
}

interface PressActInputQQState {
  inputValue: string;
}

export default class ActInputQQ extends Component<ActInputQQProps, PressActInputQQState> {
  constructor(props: ActInputQQProps) {
    super(props);
    this.state = {
      inputValue: props.qqNumber || '',
    };
  }

  handleInputChange = (e: Event) => {
    const target = e.target as HTMLInputElement;
    const { value } = target;
    this.setState({ inputValue: value });

    // 触发双向绑定回调
    if (this.props.onQQNumberChange) {
      this.props.onQQNumberChange(value);
    }
  };

  closeDialog = () => {
    if (this.props.closeDialog) {
      this.props.closeDialog();
    }
  };

  handleConfirm = () => {
    if (this.props.onClickButton) {
      // 传递当前输入框的值给确认回调
      this.props.onClickButton(this.state.inputValue);
    }
  };

  onClickCancel = () => {
    if (this.props.onClickCancel) {
      this.props.onClickCancel();
    }
  };

  render() {
    const { show = false, title } = this.props;
    const { inputValue } = this.state;

    if (!show) {
      return null;
    }

    return (
      <PopupContainer
        title={title}
        size='small'
        cancelText='取消'
        confirmText='确认兑换'
        onClickClose={this.closeDialog}
        onClickConfirm={this.handleConfirm}
        onClickCancel={this.onClickCancel}
      >
        <div className={styles['qq-dialog-wrapper']}>
          {/* QQ号输入框 */}
          <div className={styles['input-container']}>
            <input
              type="text"
              value={inputValue}
              placeholder="请输入QQ帐号"
              className={styles['qq-input']}
              onInput={this.handleInputChange}
            />
          </div>
        </div>
      </PopupContainer>
    );
  }
}
