import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { fetch } from '@/utils/request'
import { resolvePath } from '@/constants/api'
import track from '@/utils/tracking/track'

const addLike = (type, id) => fetch({ url: resolvePath(`${type}/like/${id}`),  method: 'POST' })
const cancelLike = (type, id) => fetch({ url: resolvePath(`${type}/like/${id}`),  method: 'POST' })

export default function(liked, options = {}) {
  const { id, eventType } = options
  const [isLiked, setIsLiked] = useState(liked)

  useEffect(() => setIsLiked(liked), [liked])

  const handleLike = () => {
    if (isLiked) {
      cancelLike(eventType, id).then(() => {
        setIsLiked(false)
        Taro.showToast({
          title: '已取消点赞',
          icon: 'none',
        })
      })
    } else {
      addLike(eventType, id).then(() => {
        setIsLiked(true)
        Taro.showToast({
          title: '点赞成功',
          icon: 'none',
        })
      })
    }
    track({
      event: 'save',
      ...options,
    })
  }

  return [isLiked, handleLike];
}
