import { View, Input } from '@tarojs/components'
import { Button } from '@/components/ui/button'
import Taro from '@tarojs/taro'
import { useState, useEffect } from 'react'
import './index.css'

interface QuantitySelectorProps {
  /** 当前数量 */
  value: number
  /** 数量变化时的回调函数 */
  onChange: (quantity: number) => void
  /** 最大可购买数量（考虑库存和单次购买限制） */
  maxQuantity?: number
  /** 商品库存 */
  stock?: number
  /** 是否禁用 */
  disabled?: boolean
  /** 自定义类名 */
  className?: string
  /** 是否阻止事件冒泡 */
  stopPropagation?: boolean
  /** 样式变体：'default' 为购物车样式（窄输入框），'detail' 为商品详情样式（宽输入框） */
  variant?: 'default' | 'detail'
}

export function QuantitySelector({
  value,
  onChange,
  maxQuantity = 999,
  stock = 999,
  disabled = false,
  className = '',
  stopPropagation = true,
  variant = 'default'
}: QuantitySelectorProps) {
  const [localQuantity, setLocalQuantity] = useState(value)
  const [inputValue, setInputValue] = useState(value === 0 ? '' : value.toString())

  // 同步外部value变化
  useEffect(() => {
    setLocalQuantity(value)
    setInputValue(value === 0 ? '' : value.toString())
  }, [value])

  // 获取实际最大可购买数量
  const getActualMaxQuantity = () => {
    return Math.min(stock, maxQuantity)
  }

  // 处理减少数量
  const handleDecrease = (e?: any) => {
    if (stopPropagation && e) {
      e.stopPropagation()
    }

    if (disabled) return

    const currentQty = localQuantity === 0 ? 1 : localQuantity
    const newQuantity = Math.max(1, currentQty - 1)
    setLocalQuantity(newQuantity)
    setInputValue(newQuantity.toString())
    onChange(newQuantity)
  }

  // 处理增加数量
  const handleIncrease = (e?: any) => {
    if (stopPropagation && e) {
      e.stopPropagation()
    }

    if (disabled) return

    const currentQty = localQuantity === 0 ? 1 : localQuantity
    const actualMaxQuantity = getActualMaxQuantity()

    if (currentQty >= actualMaxQuantity) {
      if (actualMaxQuantity === stock) {
        Taro.showToast({
          title: `库存只有${stock}件`,
          icon: 'none',
          duration: 1500
        })
      } else {
        Taro.showToast({
          title: `单次最多购买${maxQuantity}件`,
          icon: 'none',
          duration: 1500
        })
      }
      return
    }

    const newQuantity = currentQty + 1
    setLocalQuantity(newQuantity)
    setInputValue(newQuantity.toString())
    onChange(newQuantity)
  }

  // 处理数量输入变化
  const handleQuantityChange = (e: any) => {
    if (stopPropagation && e) {
      e.stopPropagation()
    }

    const value = e.detail.value
    if (disabled) return

    // 清除非数字字符
    const cleanedValue = value.replace(/[^\d]/g, '')

    // 如果输入为空，设为空字符串（允许用户删除）
    if (cleanedValue === '') {
      setInputValue('')
      setLocalQuantity(0)
      onChange(0)
      return
    }

    const numValue = parseInt(cleanedValue)

    // 验证最小值
    if (numValue < 1) {
      setInputValue('1')
      setLocalQuantity(1)
      onChange(1)
      Taro.showToast({
        title: '数量不能小于1',
        icon: 'none',
        duration: 1500
      })
      return
    }

    // 验证最大值
    const actualMaxQuantity = getActualMaxQuantity()
    if (numValue > actualMaxQuantity) {
      setInputValue(actualMaxQuantity.toString())
      setLocalQuantity(actualMaxQuantity)
      onChange(actualMaxQuantity)
      if (actualMaxQuantity === stock) {
        Taro.showToast({
          title: `库存只有${stock}件`,
          icon: 'none',
          duration: 1500
        })
      } else {
        Taro.showToast({
          title: `单次最多购买${maxQuantity}件`,
          icon: 'none',
          duration: 1500
        })
      }
      return
    }

    setInputValue(cleanedValue)
    setLocalQuantity(numValue)
    onChange(numValue)
  }

  // 处理输入框失去焦点（完成输入）
  const handleQuantityBlur = (e?: any) => {
    if (stopPropagation && e) {
      e.stopPropagation()
    }

    if (disabled) return

    // 如果数量为0（表示空输入），设为1
    if (localQuantity === 0) {
      setInputValue('1')
      setLocalQuantity(1)
      onChange(1)
    }
  }

  return (
    <View className={`quantity-controls ${className} quantity-${variant}`}>
      <Button
        size="sm"
        variant="ghost"
        className="quantity-btn"
        onClick={handleDecrease}
        disabled={disabled || localQuantity <= 1}
      >
        -
      </Button>
      <Input
        className="quantity-input"
        type="number"
        value={inputValue}
        onInput={handleQuantityChange}
        onBlur={handleQuantityBlur}
        placeholder="1"
        maxlength={3}
        confirmType="done"
        disabled={disabled}
      />
      <Button
        size="sm"
        variant="ghost"
        className="quantity-btn"
        onClick={handleIncrease}
        disabled={disabled || localQuantity >= getActualMaxQuantity()}
      >
        +
      </Button>
    </View>
  )
}