import {CSSProperties, FC, useCallback, useEffect, useState} from "react";
import star from '@/static/img/star.png'
import starLine from '@/static/img/starLine.png'
import {Image, View} from "@tarojs/components";
import styles from './collect.module.scss'
import {Profile} from "@/store"
import Taro from "@tarojs/taro";
import {userApi} from "@/api";

interface Props {
  onClick?: () => void
  select?: boolean
  stylesImage?: CSSProperties
  styles?: CSSProperties
  owner_id: number
  owner_type: CreateOwnerType
  textHidden?: boolean
}

/** 收藏 */
const Collect: FC<Props> = (props) => {
  const {token} = Profile.useContainer()
  const [loading, setLoading] = useState(false)
  const [select, setSelect] = useState(props.select)

  useEffect(() => {
    setSelect(props.select)
  }, [props])

  const change = useCallback(async () => {
    if (!token) {
      Taro.navigateTo({url: '/pages/login/login'})
      return
    }
    if (loading) return;
    props.onClick?.()
    console.log(select)
    setSelect(!select)
    setLoading(true)
    await userApi.create({owner_id: props.owner_id, owner_type: props.owner_type})
    setTimeout(() => {
      setLoading(false)
    }, 300)
  }, [loading, token, select])

  return (
    <View className={styles.collect} onClick={change} style={props.styles}>
      <View className={styles.collectImage} style={props.stylesImage}>
        <View className={`${loading && select && styles.zoom}`}/>
        <Image
          src={(select && token) ? star : starLine}
          className={`${loading && styles.pulse}`}/>
      </View>
      {!props.textHidden && (select ? '已收藏' : '收藏')}
    </View>
  )
}

export default Collect
