import { View, Text, ScrollView } from '@tarojs/components'
import { Button } from '@/components/ui/button'
import { useState, useEffect } from 'react'

interface SpecOption {
  id: number
  name: string
  price: number
  stock: number
  image?: string
}

interface SpecSelectorProps {
  visible: boolean
  onClose: () => void
  onConfirm: (selectedSpec: SpecOption | null, quantity: number) => void
  goodsId: number
  currentSpec?: string
  currentQuantity?: number
}

export function GoodsSpecSelector({
  visible,
  onClose,
  onConfirm,
  goodsId: _goodsId,
  currentSpec,
  currentQuantity = 1
}: SpecSelectorProps) {
  const [selectedSpec, setSelectedSpec] = useState<SpecOption | null>(null)
  const [quantity, setQuantity] = useState(currentQuantity)
  const [specOptions, setSpecOptions] = useState<SpecOption[]>([])

  // 模拟从API获取规格数据
  useEffect(() => {
    if (visible) {
      // 这里应该调用真实的SKU API
      // 目前使用模拟数据，但价格应该基于商品基础价格进行合理变化
      const mockSpecs: SpecOption[] = [
        { id: 1, name: '标准版', price: 299, stock: 100 },
        { id: 2, name: '豪华版', price: 399, stock: 50 },
        { id: 3, name: '旗舰版', price: 499, stock: 20 }
      ]
      setSpecOptions(mockSpecs)

      // 如果有当前选中的规格，设置选中状态
      if (currentSpec) {
        const foundSpec = mockSpecs.find(spec => spec.name === currentSpec)
        if (foundSpec) {
          setSelectedSpec(foundSpec)
        }
      }
    }
  }, [visible, currentSpec])

  const handleSpecSelect = (spec: SpecOption) => {
    setSelectedSpec(spec)
    // 重置数量为1
    setQuantity(1)
  }

  // 计算总价
  const calculateTotalPrice = () => {
    if (!selectedSpec) return 0
    return selectedSpec.price * quantity
  }

  // 验证价格计算正确性
  const validatePriceCalculation = () => {
    if (selectedSpec && quantity > 0) {
      const calculatedPrice = calculateTotalPrice()
      const expectedPrice = selectedSpec.price * quantity

      if (calculatedPrice !== expectedPrice) {
        console.error('价格计算错误:', { calculatedPrice, expectedPrice, specPrice: selectedSpec.price, quantity })
      }
    }
  }

  // 在数量或规格变化时验证价格计算
  useEffect(() => {
    validatePriceCalculation()
  }, [selectedSpec, quantity])

  const handleQuantityChange = (change: number) => {
    if (!selectedSpec) return

    const newQuantity = quantity + change
    if (newQuantity >= 1 && newQuantity <= selectedSpec.stock) {
      setQuantity(newQuantity)
    }
  }

  const handleConfirm = () => {
    if (!selectedSpec) {
      // 提示用户选择规格
      return
    }
    onConfirm(selectedSpec, quantity)
    onClose()
  }

  if (!visible) return null

  return (
    <View className="spec-modal">
      <View className="spec-modal-content">
        <View className="spec-modal-header">
          <Text className="spec-modal-title">选择规格</Text>
          <View
            className="spec-modal-close"
            onClick={onClose}
          >
            <View className="i-heroicons-x-mark-20-solid" />
          </View>
        </View>

        <ScrollView className="spec-options" scrollY>
          {specOptions.map(spec => (
            <View
              key={spec.id}
              className={`spec-option ${selectedSpec?.id === spec.id ? 'selected' : ''}`}
              onClick={() => handleSpecSelect(spec)}
            >
              <Text className="spec-option-text">{spec.name}</Text>
              <View className="spec-option-price">
                <Text className="price-text">¥{spec.price.toFixed(2)}</Text>
                <Text className="stock-text">库存: {spec.stock}</Text>
              </View>
            </View>
          ))}
        </ScrollView>

        {/* 数量选择器 */}
        {selectedSpec && (
          <View className="quantity-section">
            <Text className="quantity-label">数量</Text>
            <View className="quantity-controls">
              <Button
                size="sm"
                variant="ghost"
                className="quantity-btn"
                onClick={() => handleQuantityChange(-1)}
                disabled={quantity <= 1}
              >
                -
              </Button>
              <Text className="quantity-value">{quantity}</Text>
              <Button
                size="sm"
                variant="ghost"
                className="quantity-btn"
                onClick={() => handleQuantityChange(1)}
                disabled={quantity >= selectedSpec.stock}
              >
                +
              </Button>
            </View>
          </View>
        )}

        <View className="spec-modal-footer">
          <Button
            className="spec-confirm-btn"
            onClick={handleConfirm}
            disabled={!selectedSpec}
          >
            {selectedSpec ? `确定 (¥${calculateTotalPrice().toFixed(2)})` : '请选择规格'}
          </Button>
        </View>
      </View>
    </View>
  )
}