'use client'

import { useState } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { Check, ShoppingCart } from 'lucide-react'
import type { CartItem } from '@/components/providers/AppProvider'
import { useApp } from '@/components/providers/AppProvider'
import type { CourseAccessState, MembershipLevel } from '@/types'

interface AddToCartButtonProps {
  item: CartItem
  className?: string
  label?: string
  requiredMembershipLevel?: MembershipLevel
  membershipAccess?: Partial<Record<MembershipLevel, CourseAccessState>>
  membershipPrices?: Partial<Record<MembershipLevel, number>>
  directOrderOnFree?: boolean
  disabled?: boolean
  disabledLabel?: string
}

function membershipGateLabel(level: MembershipLevel) {
  if (level === 1) return '会员专享'
  if (level === 2) return '高级会员专享'
  return ''
}

function completedLabel(type: CartItem['type']) {
  if (type === 'course') return '已加入课程'
  if (type === 'event') return '已报名'
  if (type === 'agent') return '已开通'
  if (type === 'data') return '已获取'
  return '已完成'
}

function accessBlockedLabel(level: MembershipLevel) {
  if (level === 2) return '高级会员专享'
  if (level === 1) return '会员专享'
  return '会员专享'
}

function userPriceForAccess(level: MembershipLevel, itemPrice: number, access?: CourseAccessState, membershipPrices?: Partial<Record<MembershipLevel, number>>) {
  if (access === 'free') return 0
  if (access === 'closed') return itemPrice
  if (!membershipPrices) return itemPrice
  if (membershipPrices[level] != null) return Math.max(0, Number(membershipPrices[level]))
  return itemPrice
}

export function AddToCartButton({ item, className = '', label = '加入购物车', requiredMembershipLevel = 0, membershipAccess, membershipPrices, directOrderOnFree = false, disabled = false, disabledLabel = '不可购买' }: AddToCartButtonProps) {
  const { addCartItem, cartItems, orders, user } = useApp()
  const router = useRouter()
  const pathname = usePathname()
  const [justAdded, setJustAdded] = useState(false)
  const exists = Boolean(user && cartItems.some((cartItem) => cartItem.id === item.id && cartItem.type === item.type))
  const currentAccess = user && membershipAccess ? membershipAccess[user.membershipLevel] : undefined
  const currentPrice = user ? userPriceForAccess(user.membershipLevel, item.price, currentAccess, membershipPrices) : item.price
  const itemForCurrentUser = { ...item, price: currentPrice }
  const directOrderCompleted = Boolean(
    user &&
    directOrderOnFree &&
    itemForCurrentUser.price === 0 &&
    orders.some((order) => order.items.some((orderItem) => orderItem.id === item.id && orderItem.type === item.type)),
  )
  const membershipBlocked = requiredMembershipLevel > 0 && Boolean(user && user.membershipLevel < requiredMembershipLevel)
  const accessBlocked = currentAccess === 'closed'
  const gateLabel = membershipGateLabel(requiredMembershipLevel)

  function handleClick() {
    if (disabled || membershipBlocked || accessBlocked || directOrderCompleted) {
      return
    }

    if (!user) {
      const redirect = encodeURIComponent(pathname || item.href)
      router.push(`/login-required?redirect=${redirect}&action=${item.type}`)
      return
    }

    if (!user.onboardingCompleted) {
      const redirect = encodeURIComponent(pathname || item.href)
      router.push(`/onboarding?redirect=${redirect}`)
      return
    }

    if (directOrderOnFree && itemForCurrentUser.price === 0) {
      addCartItem(itemForCurrentUser)
      router.push('/checkout')
      return
    }

    const added = addCartItem(itemForCurrentUser)
    if (!added) return
    setJustAdded(true)
    window.setTimeout(() => setJustAdded(false), 1500)
  }

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={disabled || membershipBlocked || accessBlocked || directOrderCompleted}
      className={`inline-flex min-h-10 items-center justify-center gap-2 rounded-[4px] px-4 py-2 text-sm font-bold transition-colors ${
        disabled || membershipBlocked || accessBlocked || directOrderCompleted ? 'cursor-not-allowed border border-line bg-bg text-soft hover:bg-bg' : className
      }`}
    >
      {!disabled && !membershipBlocked && !accessBlocked && (directOrderCompleted || exists || justAdded ? <Check className="h-4 w-4" /> : <ShoppingCart className="h-4 w-4" />)}
      {disabled ? disabledLabel : membershipBlocked ? gateLabel : accessBlocked && user ? accessBlockedLabel(user.membershipLevel) : directOrderCompleted ? completedLabel(item.type) : exists ? '已在购物车' : justAdded ? '已加入' : label}
    </button>
  )
}
