import { useState, useCallback } from 'react'
import {
  listShopUserCoupon,
  pageShopUserCoupon,
  removeShopUserCoupon,
  getMyAvailableCoupons,
  getMyUsedCoupons,
  getMyExpiredCoupons,
} from '@/api/shop/shopUserCoupon'
import type { ShopUserCoupon } from '@/api/shop/shopUserCoupon/model'

export type CouponTab = 'available' | 'used' | 'expired'

interface UseCouponReturn {
  coupons: ShopUserCoupon[]
  loading: boolean
  tab: CouponTab
  setTab: (tab: CouponTab) => void
  loadCoupons: () => Promise<void>
  deleteCoupon: (id: string) => Promise<boolean>
}

export function useCoupon(): UseCouponReturn {
  const [coupons, setCoupons] = useState<ShopUserCoupon[]>([])
  const [loading, setLoading] = useState(false)
  const [tab, setTab] = useState<CouponTab>('available')

  const loadCoupons = useCallback(async () => {
    setLoading(true)
    try {
      let list: ShopUserCoupon[] = []
      switch (tab) {
        case 'available':
          list = await getMyAvailableCoupons()
          break
        case 'used':
          list = await getMyUsedCoupons()
          break
        case 'expired':
          list = await getMyExpiredCoupons()
          break
      }
      setCoupons(list || [])
    } catch (error) {
      console.error('Load coupons error:', error)
    } finally {
      setLoading(false)
    }
  }, [tab])

  const deleteCoupon = useCallback(async (id: string): Promise<boolean> => {
    try {
      await removeShopUserCoupon(Number(id))
      setCoupons(prev => prev.filter(c => c.id !== id))
      return true
    } catch {
      return false
    }
  }, [])

  return { coupons, loading, tab, setTab, loadCoupons, deleteCoupon }
}

// 获取优惠券类型文本
export function getCouponTypeText(type?: number): string {
  switch (type) {
    case 10: return '满减券'
    case 20: return '折扣券'
    case 30: return '免费券'
    case 40: return '无门槛券'
    case 50: return '场地使用券'
    default: return '优惠券'
  }
}

// 获取优惠券状态文本
export function getCouponStatusText(coupon: ShopUserCoupon): string {
  if (coupon.status === 1) return '已使用'
  if (coupon.status === 2 || coupon.isExpire === 1) return '已过期'
  return '未使用'
}

// 格式化优惠券金额
export function formatCouponValue(coupon: ShopUserCoupon): string {
  switch (coupon.type) {
    case 20:
      // 折扣券
      return `${coupon.discount || 0}折`
    case 40:
      // 无门槛券
      return `¥${coupon.reducePrice || '0'}`
    case 50:
      // 场地使用券
      return coupon.useCount && coupon.useCount > 0 ? `${coupon.useCount}次` : '不限次'
    default:
      // 满减券/免费券
      return `¥${coupon.reducePrice || '0'}`
  }
}

// 检查优惠券是否即将过期（3天内）
export function isExpiringSoon(coupon: ShopUserCoupon): boolean {
  return coupon.isExpiringSoon === true || (coupon.daysRemaining !== undefined && coupon.daysRemaining <= 3)
}
