import {ChangeEvent} from 'react'
import {Dayjs} from 'dayjs'
import {TypeInnerDatePicker} from './create-inner-date-picker'
import {InnerRangePicker} from './inner-range-picker'

export function handleUserInputChange(
    {
        e,
        comp,

        // @todo: 暂时注释掉, 目前没被用到, 但未来可能会被用上 @liang:2021-06-16
        // itemFormatProp,

        valueProp,
        displayedProp,
        inputTextProp,
        isInputProp,

        onCustomChange,
    }: {
        e: ChangeEvent
        comp: TypeInnerDatePicker | InnerRangePicker

        itemFormatProp: 'computedItemFormat'
        valueProp: 'value' | 'startValue' | 'endValue'
        displayedProp: 'displayedDate' | 'startDisplayedDate' | 'endDisplayedDate'
        inputTextProp: 'userInputText' | 'startUserInputText' | 'endUserInputText'
        isInputProp: 'isUserInput' | 'isStartUserInput' | 'isEndUserInput'

        onCustomChange: (
            value: Dayjs | null,
            displayDate: Dayjs,
        ) => void
    }
) {
    const text = (e.target as HTMLInputElement).value
    const trimmedText = text.trim()

    const tryParsedDate = comp.computedItemValueExtractor(trimmedText)

    // @ts-ignore 动态 key 问题
    let value = comp.state[valueProp] as null | Dayjs

    // @ts-ignore 动态 key 问题
    let displayedDate = comp.state[displayedProp] as Dayjs

    if (
        tryParsedDate.isValid()

    // @todo:review 考虑一下是否严格进行日期控制? 2019-11-1 到底合法不合法?
    // 是否必须要进行严格的合规性校验?
    // && tryParsedDate.format(itemFormat) === trimmedText
    ) {
        value = tryParsedDate
        displayedDate = tryParsedDate
    }

    if (!trimmedText) {
        value = null
    }

    // @ts-ignore 动态 key 问题
    comp.setState({
        [isInputProp]: true,
        [inputTextProp]: trimmedText,
    })

    if (onCustomChange) {
        onCustomChange(value, displayedDate)
    }
}
