import { Image, RootPortal, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { FC, forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Popup from '@/components/popup'

interface UploadColorEvent {
  onUploadConfirm?: Function
}

interface PropsType extends UploadColorEvent {
  uploadConfirmState: boolean
}

const UploadColor = (params: PropsType, ref) => {
  const { onUploadConfirm, uploadConfirmState } = params
  const [showModal, setShowModal] = useState(false)
  const [filePath, setFilePath] = useState('')
  const [file, setFile] = useState({})

  const handleUpload = async() => {
    Taro.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success(ev) {
        setFilePath(ev.tempFiles[0].tempFilePath)
        setFile(ev.tempFiles[0])
      },
    })
  }

  const handleTriggerUploadModal = (bool: boolean) => {
    setShowModal(bool)
  }
  useImperativeHandle(
    ref,
    () => ({
      handleTriggerUploadModal,
    }),
    [handleTriggerUploadModal],
  )

  const handleClear = () => {
    setFilePath('')
  }
  const handleUploadConfirm = () => {
    onUploadConfirm && onUploadConfirm(file)
  }
  useEffect(() => {
    if (uploadConfirmState) {
      setFilePath('')
      handleTriggerUploadModal(false)
    }
  }, [uploadConfirmState])
  return (
    <View className={styles['upload-container']}>
      <Popup title="上传纹理" show={showModal} onClose={() => handleTriggerUploadModal(false)}>
        <View className={styles['u-content']}>
          <View onClick={handleUpload} className={styles['u-image']}>
            {filePath && <Image mode="aspectFill" src={filePath} />}

            <View className={classnames({ 'update-statu': filePath })}>{filePath ? '点击修改' : '点击上传'}</View>
          </View>
          <View className={styles['u-button']}>
            <View onClick={handleClear}>清除</View>
            <View onClick={handleUploadConfirm} className={styles.confirm}>
              确定
            </View>
          </View>
        </View>
      </Popup>
    </View>
  )
}
export default forwardRef(UploadColor)
