import { View, Text, ScrollView } from '@tarojs/components'
import { Button } from '@/components/ui/button'
import { useState, useEffect } from 'react'
import { goodsClient } from '@/api'
import './index.css'

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

interface GoodsFromApi {
  id: number
  name: string
  price: number
  stock: number
  imageFile?: { fullUrl: string }
}

interface SpecSelectorProps {
  visible: boolean
  onClose: () => void
  onConfirm: (selectedSpec: SpecOption | null, quantity: number, actionType?: 'add-to-cart' | 'buy-now') => void
  parentGoodsId: number
  currentSpec?: string
  currentQuantity?: number
  actionType?: 'add-to-cart' | 'buy-now'
}

export function GoodsSpecSelector({
  visible,
  onClose,
  onConfirm,
  parentGoodsId,
  currentSpec,
  currentQuantity = 1,
  actionType
}: SpecSelectorProps) {
  const [selectedSpec, setSelectedSpec] = useState<SpecOption | null>(null)
  const [quantity, setQuantity] = useState(currentQuantity)
  const [specOptions, setSpecOptions] = useState<SpecOption[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 从API获取子商品数据作为规格选项
  useEffect(() => {
    // 重置状态
    setSpecOptions([])
    setSelectedSpec(null)
    setError(null)

    if (visible && parentGoodsId > 0) {
      // 调用真实的子商品列表API
      const fetchChildGoods = async () => {
        setIsLoading(true)
        setError(null)

        try {
          const response = await goodsClient[':id'].children.$get({
            param: { id: parentGoodsId },
            query: {
              page: 1,
              pageSize: 100, // 获取所有子商品，假设不会超过100个
              sortBy: 'createdAt',
              sortOrder: 'ASC'
            }
          })

          if (response.status === 200) {
            const data = await response.json()
            // 将子商品数据转换为规格选项格式
            const childGoodsAsSpecs: SpecOption[] = data.data.map((goods: GoodsFromApi) => ({
              id: goods.id, // 子商品ID
              name: goods.name, // 子商品名称作为规格名称
              price: goods.price,
              stock: goods.stock,
              image: goods.imageFile?.fullUrl
            }))
            setSpecOptions(childGoodsAsSpecs)

            // 如果有当前选中的规格，设置选中状态
            if (currentSpec) {
              const foundSpec = childGoodsAsSpecs.find(spec => spec.name === currentSpec)
              if (foundSpec) {
                setSelectedSpec(foundSpec)
              }
            }
          } else {
            // 尝试解析响应体获取具体错误消息
            let errorMsg = `获取子商品列表失败: ${response.status}`
            try {
              const errorData = await response.json()
              if (errorData && errorData.message) {
                errorMsg = errorData.message
              }
            } catch (jsonError) {
              console.warn('无法解析错误响应体:', jsonError)
            }
            console.error('获取子商品列表失败:', { status: response.status, message: errorMsg })
            setError(errorMsg)
            setSpecOptions([])
          }
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : '获取子商品列表异常'
          console.error('获取子商品列表异常:', error)
          setError(errorMsg)
          setSpecOptions([])
        } finally {
          setIsLoading(false)
        }
      }

      fetchChildGoods()
    } else {
      // 如果不可见或parentGoodsId无效，清空规格选项
      setIsLoading(false)
    }
  }, [visible, parentGoodsId, 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 getConfirmButtonText = (spec: SpecOption, qty: number, action?: 'add-to-cart' | 'buy-now') => {
    const totalPrice = spec.price * qty
    const priceText = `¥${totalPrice.toFixed(2)}`

    if (action === 'add-to-cart') {
      return `加入购物车 (${priceText})`
    } else if (action === 'buy-now') {
      return `立即购买 (${priceText})`
    } else {
      return `确定 (${priceText})`
    }
  }

  const handleConfirm = () => {
    if (!selectedSpec) {
      // 提示用户选择规格
      return
    }
    onConfirm(selectedSpec, quantity, actionType)
    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>
          {isLoading ? (
            <View className="spec-loading">
              <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
              <Text className="loading-text">加载规格选项...</Text>
            </View>
          ) : error ? (
            <View className="spec-error">
              <View className="i-heroicons-exclamation-triangle-20-solid w-8 h-8 text-red-500" />
              <Text className="error-text">{error}</Text>
              <Button
                size="sm"
                variant="outline"
                className="retry-btn"
                onClick={() => {
                  // 重新触发数据获取
                  setSpecOptions([])
                  setSelectedSpec(null)
                  setError(null)
                  setIsLoading(true)
                  // 这里应该重新调用API，但useEffect会基于依赖项自动重新执行
                }}
              >
                重试
              </Button>
            </View>
          ) : specOptions.length === 0 ? (
            <View className="spec-empty">
              <View className="i-heroicons-information-circle-20-solid w-8 h-8 text-gray-400" />
              <Text className="empty-text">暂无规格选项</Text>
            </View>
          ) : (
            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 ? getConfirmButtonText(selectedSpec, quantity, actionType) : '请选择规格'}
          </Button>
        </View>
      </View>
    </View>
  )
}