/**
 * 日期选择器
 */
import Modal from 'antd-mobile/es/modal'
import React from 'react'
import { Today } from '../calendar'

import DatePickerInner from './DatePickerInner'

export interface DatePickerProps {
  value?: Date
  title?: string
  onChange?: (value: Date) => void
  disabledBefore?: Date
  disabledAfter?: Date
  children: (
    value: Date,
    onClick: () => void,
    visible: boolean,
  ) => React.ReactNode
}

interface DatePickerState {
  visible: boolean
  value?: Date
}

export default class DatePicker extends React.PureComponent<
  DatePickerProps,
  DatePickerState
> {
  public static defaultProps = {
    title: '选择日期',
  }

  public state: DatePickerState = {
    visible: false,
    value: this.props.value,
  }

  public componentDidUpdate(preProps: DatePickerProps) {
    if (preProps.value !== this.props.value) {
      this.setState({ value: this.props.value })
    }
  }

  public render() {
    const { children, title, ...other } = this.props
    const { visible, value } = this.state
    return (
      <>
        {children(other.value || Today, this.handleShow, visible)}
        <Modal
          transparent
          maskClosable={false}
          visible={!!visible}
          className="jm-date-picker"
          wrapClassName="jm-date-picker__wrapper"
        >
          <div className="jm-date-picker__header-bar">
            <div className="jm-date-picker__action" onClick={this.handleCancel}>
              取消
            </div>
            <div className="jm-date-picker__title">{title}</div>
            <div className="jm-date-picker__action" onClick={this.handleOk}>
              确定
            </div>
          </div>
          <DatePickerInner
            {...other}
            onChange={this.handleChange}
            value={value}
          />
        </Modal>
      </>
    )
  }

  private handleChange = (value: Date) => {
    this.setState({ value })
  }

  private reset() {
    this.setState({ value: this.props.value })
  }

  private handleOk = () => {
    this.setState({ visible: false })
    setTimeout(() => {
      if (this.props.onChange) {
        this.props.onChange(this.state.value!)
      }
    }, 400)
  }

  private handleCancel = () => {
    this.setState({ visible: false })
    this.reset()
  }

  private handleShow = () => {
    this.setState({ visible: true })
  }
}
