import React, { useState, useEffect, useCallback } from 'react'
import Picker from './Picker'
import { renderYearMonth, renderHourMinute } from './PickerData'
interface PickerOption {
  text: string | number
  value: string | number
}

interface PickerProps {
  options?: PickerOption[][]
  value?: (string | number)[]
  type?: 'month' | 'hour' |  null
  onConfirm?: (options: PickerOption[], values: (string | number)[]) => void
  onChange?: ( value: (string | number)[] ) => void
}

export interface PickerCommonRef {
  getValue: () => (string | number)[]
  setValue: (v: (string | number)[]) => void
}

const PopupPicker = ({ 
  value = [], 
  onChange,
  options = [],
  type = null
}: PickerProps, ref: React.Ref<PickerCommonRef>) => {
  const [defaultValue, setDefaultValue] = useState<(string | number)[]>([])

  const [defaultOptions, setDefaultOptions] = useState<PickerOption[][]>([])
  const changePicker = (options: any[], values: any, columnIndex: number) => {
    console.log('picker onChange', columnIndex, values, options)
    setDefaultValue(values)
  }

  useEffect(() => {
    if (type === 'month') {
      setDefaultOptions(renderYearMonth())
    } else if (type === 'hour') {
      setDefaultOptions(renderHourMinute())
    } else {
      setDefaultOptions(options)
    }
  }, [type])

  useEffect(() => {
    // 同步初始值到内部状态，供 getValue 使用
    setDefaultValue(value)
  }, [value])

  React.useImperativeHandle(ref, () => ({
    getValue: () => (defaultValue && defaultValue.length ? defaultValue : value),
    setValue: (v: (string | number)[]) => {
      setDefaultValue(v)
    },
  }), [defaultValue, value])

  return (
    <>
     <Picker
          visible={true}
          options={defaultOptions}
          defaultValue={defaultValue.length ? defaultValue : value}
          onChange={changePicker}
        />
    </>
  )
}

export default React.forwardRef<PickerCommonRef, PickerProps>(PopupPicker)
