import { View, Image, Text } from '@tarojs/components'
import TDesignIcon from '../tdesign/icon'
import { useState, useEffect } from 'react'
import { GoodsSpecSelector } from '../goods-spec-selector'
import { goodsClient } from '@/api'
import Taro from '@tarojs/taro'
import './index.css'

export interface GoodsData {
  id: string
  name?: string
  cover_image?: string
  price?: number
  originPrice?: number
  tags?: string[]
  hasSpecOptions?: boolean
  parentGoodsId?: number
  quantity?: number
  stock?: number
  image?: string
}

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

interface GoodsCardProps {
  id?: string
  data: GoodsData
  currency?: string
  onClick?: (goods: GoodsData) => void
  onAddCart?: (goods: GoodsData) => void
}

export default function GoodsCard({
  id,
  data,
  currency = '¥',
  onClick,
  onAddCart
}: GoodsCardProps) {
  const [showSpecModal, setShowSpecModal] = useState(false)
  const [selectedSpec, setSelectedSpec] = useState<SelectedSpec | null>(null)
  const [pendingAction, setPendingAction] = useState<'add-to-cart' | null>(null)
  const [allChildGoodsOutOfStock, setAllChildGoodsOutOfStock] = useState(false)

  const independentID = id || `goods-card-${Math.floor(Math.random() * 10 ** 8)}`

  // 检查多规格商品的所有子商品库存
  useEffect(() => {
    if (data.hasSpecOptions && data.parentGoodsId && data.parentGoodsId > 0) {
      const fetchChildGoodsStock = async () => {
        try {
          const response = await goodsClient[':id'].children.$get({
            param: { id: data.parentGoodsId! },
            query: {
              page: 1,
              pageSize: 100, // 获取所有子商品
              sortBy: 'createdAt',
              sortOrder: 'ASC'
            }
          })

          if (response.status === 200) {
            const result = await response.json()
            const childGoods = result.data || []

            // 检查是否所有子商品库存都为0
            const allOutOfStock = childGoods.length > 0 &&
              childGoods.every((goods: any) => (goods.stock || 0) <= 0)

            setAllChildGoodsOutOfStock(allOutOfStock)
          }
        } catch (error) {
          console.error('获取子商品库存失败:', error)
        }
      }

      fetchChildGoodsStock()
    } else {
      // 单规格商品，重置状态
      setAllChildGoodsOutOfStock(false)
    }
  }, [data.hasSpecOptions, data.parentGoodsId])

  const handleClick = () => {
    onClick?.(data)
  }

  // 移除单独的图片点击事件，改为整个卡片统一处理
  // const handleThumbClick = (e: any) => {
  //   e.stopPropagation()
  //   onThumbClick?.(data)
  // }

  const handleAddCart = (e: any) => {
    e.stopPropagation()

    // 检查商品是否无货
    const isOutOfStock = (data.stock !== undefined && data.stock <= 0) || allChildGoodsOutOfStock
    if (isOutOfStock) {
      Taro.showToast({
        title: '商品已售罄',
        icon: 'none',
        duration: 1500
      })
      return
    }

    // 检查是否有规格选项
    if (data.hasSpecOptions && data.parentGoodsId && data.parentGoodsId > 0) {
      // 有多规格选项，弹出规格选择器
      setPendingAction('add-to-cart')
      setShowSpecModal(true)
    } else {
      // 单规格商品，直接添加到购物车
      onAddCart?.(data)
    }
  }

  const handleSpecConfirm = (spec: SelectedSpec | null, quantity: number, actionType?: 'add-to-cart' | 'buy-now') => {
    console.debug('[goods-card] handleSpecConfirm called', { spec, quantity, actionType, specId: spec?.id, specIdType: typeof spec?.id })
    if (spec && actionType === 'add-to-cart' && onAddCart) {
      // 执行添加购物车操作
      console.debug('[goods-card] Calling onAddCart with goods data:', {
        id: String(spec.id),
        parentGoodsId: data.parentGoodsId,
        name: spec.name,
        price: spec.price,
        quantity,
        stock: spec.stock
      })
      onAddCart({
        ...data,
        id: String(spec.id), // 安全转换为字符串以匹配GoodsData接口
        parentGoodsId: data.parentGoodsId,
        name: spec.name,  // 子商品名称（规格名称）
        price: spec.price,
        quantity: quantity,
        stock: spec.stock,
        image: spec.image || data.cover_image // 使用规格图片或商品封面图片
      })
      setSelectedSpec(spec)
    }
    setShowSpecModal(false)
    setPendingAction(null)
  }

  const formatPrice = (price?: number) => {
    if (!price) return ''
    return price.toFixed(2)
  }

  // const isValidityLinePrice = data.originPrice && data.price && data.originPrice >= data.price

  return (
    <>
      <View
      id={independentID}
      className="goods-card"
      onClick={handleClick}
      data-goods={data}
    >
      <View className="goods-card__main">
        {/* 商品图片 */}
        <View className="goods-card__thumb">
          {data.cover_image && (
            <>
              <Image
                src={data.cover_image}
                mode="aspectFill"
                className="goods-card__img"
                lazyLoad
              />
              {(data.stock !== undefined && data.stock <= 0) || allChildGoodsOutOfStock ? (
                <View className="goods-card__out-of-stock">
                  <Text className="goods-card__out-of-stock-text">无货</Text>
                </View>
              ) : null}
            </>
          )}
        </View>

        {/* 商品信息 */}
        <View className="goods-card__body">
          <View className="goods-card__upper">
            {/* 商品标题 */}
            {data.name && (
              <Text className="goods-card__title">
                {data.name}
              </Text>
            )}

            {/* 商品标签 */}
            {/* {data.tags && data.tags.length > 0 && (
              <View className="goods-card__tags">
                {data.tags.map((tag, index) => (
                  <Text key={index} className="goods-card__tag">
                    {tag}
                  </Text>
                ))}
              </View>
            )} */}
          </View>

          <View className="goods-card__down">
            {/* 价格区域 */}
            {data.price && (
              <View className="goods-card__price">
                <Text className="goods-card__symbol">{currency}</Text>
                <Text className="goods-card__current-price">
                  {formatPrice(data.price)}
                </Text>
                {/* {data.originPrice && isValidityLinePrice && (
                  <Text className="goods-card__origin-price">
                    {currency}{formatPrice(data.originPrice)}
                  </Text>
                )} */}
              </View>
            )}

            {/* 购物车按钮 */}
            <View className="goods-card__add-cart" onClick={handleAddCart}>
              <TDesignIcon
                name="shopping-cart"
                size="64rpx"
                color="#FA550F"
              />
            </View>
          </View>
        </View>
      </View>
    </View>

    <GoodsSpecSelector
      visible={showSpecModal}
      onClose={() => {
        setShowSpecModal(false)
        setPendingAction(null) // 重置待处理操作
      }}
      onConfirm={handleSpecConfirm}
      parentGoodsId={data.parentGoodsId || 0}
      actionType={pendingAction || undefined}
    />
    </>
  )
}