import '~/styles/share.scss'
import { Popup, Tabs, Toast } from 'react-vant'
import ProductItem from '~/components/ProductItem'
import store from '~/store'
import { observer } from 'mobx-react'
import { toFixed2 } from '~/utils'
import { useMemo, useRef, useState } from 'react'
import { open_page, reset_name, upload_image } from '~/api'
import { useRouter } from '~/hooks/useRouter'

const Share = () => {

  const { userInfo, token, likeNft, myNft } = store.state
  const { push } = useRouter()
  const [visible, setVisible] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)
  const nameRef = useRef<HTMLInputElement>(null)
  const [edit, setEdit] = useState(false)
  const prevent = useRef(false) //阻止重複點擊
  const fileRef = useRef(null as any)
  const [tempUrl, setTempUrl] = useState(null as any)
  const tabs = useMemo(() => ['我的NFT', '我喜歡的NFT'], [])

  const avatarmenuClick = (event: any) => {
    const dataType = event.target.dataset.type;

    switch (dataType) {
      case "photo": //相册
        inputRef.current?.click()
        break
      case "save": //保存
        !fileRef.current && Toast.info('請選擇圖片')
        fileRef.current && uploader(fileRef.current)
        break
      case "cancel": //取消
        closePopup()
        break
    }
  }

  const uploader = async (file: File | null) => {
    if (!file) return
    setVisible(false)
    const res: any = await upload_image(file)
    res.code === 0 && await store.getUserInfo()
    res.code === 0 && Toast.success('保存成功')
    closePopup()
  }

  const saveName = async () => {
    if (nameRef.current?.value === userInfo.name) return
    const res: any = await reset_name(nameRef.current!.value)
    res.code === 0 && store.getUserInfo()
    setEdit(false)
  }

  const openPages = async () => {
    if (prevent.current) return
    prevent.current = true
    const res: any = await open_page(userInfo.show === 1 ? 2 : 1)
    res.code === 0 && store.getUserInfo()
    res.code === 0 && Toast.success({
      message: userInfo.show === 1 ? '已隐藏' : '已开放',
      forbidClick: true
    })
    prevent.current = false
  }

  const onChangeImage = (event: React.ChangeEvent<HTMLInputElement>) => {
    let file = event.target.files ? event.target.files[0] : null
    if (!file) return

    fileRef.current = file
    const reader = new FileReader()
    reader.onloadend = function () {
      const base64String = reader.result
      setTempUrl(base64String)
    }
    reader.readAsDataURL(file)
    inputRef.current!.value = ''
  }

  const closePopup = () => {
    setVisible(false)
    setTempUrl('')
    fileRef.current = null
    inputRef.current!.value = ''
  }

  return (
    <div className="share">
      <div className='box'>
        <img src={require('~/assets/personal.png')} alt="" className='bg-cover'></img>
        <div className='row-center avatar'>
          <img src={tempUrl || userInfo.url} className="img" alt="" onClick={() => {
            setVisible(true)
          }} />
        </div>
      </div>
      <div className='box-block'></div>
      {
        token ? (
          <div className='row-center mt-1 name-box'>
            {
              edit ? (
                <input type="text" ref={nameRef} onBlur={() => {
                  setTimeout(() => {
                    setEdit(false)
                  }, 100)
                }} />
              ) : (
                <div className='fz-wb-550 shar-name-overflow'>{userInfo.name}</div>
              )
            }
            <div className='ml-1'>
              {
                edit ? (
                  <i className='iconfont icon-chenggong green fz-18' onClick={saveName} />
                ) : (
                  <i className='iconfont icon-bianji' onClick={() => {
                    setEdit(true)
                    setTimeout(() => {
                      nameRef.current!.value = userInfo.name
                      nameRef.current!.focus()
                    }, 20)
                  }} />
                )
              }
            </div>
          </div>
        ) : (
          <div className='tac sub-text'>未登錄</div>
        )
      }
      <div className='row-center'>
        <div className='tag fz-wb-550 mt-5px' onClick={openPages}>{userInfo.show === 2 ? '開放我的藝術頁面' : '隱藏我的藝術頁面'}</div>
      </div>
      <div className='row-between plr-5 mt-3'>
        <div className='tac'>
          <div className='fz-20 fz-wb-550'>{userInfo.sell}</div>
          <div className='mt-8px'>售賣作品</div>
        </div>
        <div className='tac'>
          <div className='fz-20 fz-wb-550'>{userInfo.auction}</div>
          <div className='mt-8px'>拍賣作品</div>
        </div>
        <div className='tac'>
          <div className='fz-20 fz-wb-550'>{toFixed2(userInfo.income, 2)} FIL</div>
          <div className='mt-8px'>收入</div>
        </div>
      </div>
      <div className='mt-3'>
        <Tabs
          lineWidth={100}
          background="none"
          titleInactiveColor='#000'
          titleActiveColor='#000'
          color='#11C0CB'
          animated
          swipeable
        >
          {
            tabs.map((item, index) => (
              <Tabs.TabPane
                key={index}
                title={<div>
                  <span>{item}</span>
                  <span className='ml-5px' style={{ color: '#11C0CB' }}>{
                    index === 0 ? myNft.length : likeNft.length
                  }</span>
                </div>}
                titleClass='fz-wb-550'
              >
                <div className='row-between flex-wrap plr-3'>
                  {(index === 0 ? myNft : likeNft).map((item, index) => (
                    <div key={index} onClick={() => push('/detail', { id: item.id, type: item.type })}>
                      <ProductItem data={item} />
                    </div>
                  ))}
                </div>
              </Tabs.TabPane>
            ))
          }

        </Tabs>
      </div>
      <input type="file" onChange={onChangeImage} multiple={false} accept="image/*" ref={inputRef} style={{ display: 'none' }} />
      <Popup
        visible={visible}
        onClickOverlay={closePopup}
        overlayStyle={{ backgroundColor: 'rgba(0,0,0,0)' }}
        position='bottom'
        className='white'
        style={{ backgroundColor: 'rgba(60,60,60,0.9)' }}
      >
        <div className='fz-18' onClick={avatarmenuClick}>
          <div className='p-2 tac'>
            <div className='' data-type='photo'>從手機相冊選擇</div>
            <div className='mt-2' data-type='save'>保存圖片</div>
          </div>
          <div style={{ height: 2, width: '100%' }} className="background-bg"></div>
          <div className='p-2 tac' data-type="cancel">取消</div>
        </div>
      </Popup>
    </div>
  )
}

export default observer(Share)