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 addFavor = (type, id) => fetch({ url: resolvePath(`${type}/save/${id}`),  method: 'POST' })
const cancelFavor = (type, id) => fetch({ url: resolvePath(`${type}/save/${id}`),  method: 'POST' })

export default function(saved, options = {}) {
  const { id, eventType } = options
  const [isSaved, setIsSaved] = useState(saved)

  useEffect(() => setIsSaved(saved), [saved])

  const handleSave = () => {
    if (isSaved) {
      cancelFavor(eventType, id).then(() => {
        setIsSaved(false)
        Taro.showToast({
          title: '已取消收藏',
          icon: 'none',
        })
      })
    } else {
      addFavor(eventType, id).then(() => {
        setIsSaved(true)
        Taro.showToast({
          title: '收藏成功',
          icon: 'none',
        })
      })
    }
    track({
      event: 'save',
      ...options,
    })
  }

  return [isSaved, handleSave];
}
