import { View, Text, Image, ScrollView, Button } from '@tarojs/components'
import Taro, { useRouter, useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { getConfigDetail } from '../../api'
import ParticleBackground from '../../components/ParticleBackground'
import { addToCart } from '../../utils/cart'
import './detail.scss'

export default function Detail() {
  const router = useRouter()
  const { id } = router.params
  const [product, setProduct] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    if (id) fetchDetail(id)
  })

  const fetchDetail = async (id) => {
    try {
      const res = await getConfigDetail(id)
      setProduct(res)
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const handleAddToCart = () => {
    if (!product) return
    addToCart(product)
  }

  const buyNow = () => {
    if (!product) return
    Taro.navigateTo({
      url: `/pages/order/checkout?id=${product.id}&quantity=1`
    })
  }

  if (loading) return <View className='loading-screen'><Text>Loading...</Text></View>
  if (!product) return <View className='error-screen'><Text>Product Not Found</Text></View>

  return (
    <View className='page-container'>
      <ParticleBackground />
      <ScrollView scrollY className='content'>
        {/* Hero Section */}
        <View className='hero-section'>
          <View className='image-container'>
             {product.static_image_url ? (
               <Image src={product.static_image_url} mode='widthFix' className='hero-img' />
             ) : (
               <View className='placeholder-box'>
                 <Text className='icon-bolt'>⚡</Text>
               </View>
             )}
             <View className='hero-overlay' />
          </View>
          
          <View className='hero-content'>
            <Text className='hero-title'>{product.name}</Text>
            <Text className='hero-desc'>{product.description}</Text>
            
            <View className='tags-row'>
               <View className='tag cyan'><Text>{product.chip_type}</Text></View>
               {product.has_camera && <View className='tag blue'><Text>高清摄像头</Text></View>}
               {product.has_microphone && <View className='tag purple'><Text>阵列麦克风</Text></View>}
            </View>
          </View>
        </View>

        {/* Stats Section */}
        <View className='stats-card'>
           <View className='label-row'>
              <Text className='label'>售价</Text>
              <Text className='label' style={{textAlign: 'right'}}>库存</Text>
           </View>
           <View className='value-row'>
              <View className='price-box'>
                <Text className='symbol'>¥</Text>
                <Text className='price'>{product.price}</Text>
              </View>
              <View className='stock-box'>
                <Text className='stock'>{product.stock}</Text>
                <Text className='unit'>件</Text>
              </View>
           </View>
        </View>

        {/* Features Section */}
        <View className='features-section'>
           {product.features && product.features.length > 0 ? (
             product.features.map((f, idx) => {
               let iconContent
               if (f.display_icon) {
                   iconContent = <Image src={f.display_icon} className='f-icon-img' />
               } else if (f.icon_url) {
                   iconContent = <Image src={f.icon_url} className='f-icon-img' />
               } else {
                   let iconChar = '⭐'
                   let iconColor = '#00b96b'
                   switch(f.icon_name) {
                       case 'SafetyCertificate': iconChar = '🛡'; break;
                       case 'Eye': iconChar = '👁'; iconColor = '#3b82f6'; break;
                       case 'Thunderbolt': iconChar = '⚡'; iconColor = '#faad14'; break;
                       default: break;
                   }
                   iconContent = <Text className='f-icon' style={{color: iconColor}}>{iconChar}</Text>
               }

               return (
                 <View key={idx} className='feature-card'>
                   <View className='feature-icon-box'>
                      {iconContent}
                   </View>
                   <View className='feature-text'>
                     <Text className='f-title'>{f.title}</Text>
                     <Text className='f-desc'>{f.description}</Text>
                   </View>
                 </View>
               )
             })
           ) : (
             <>
                <View className='feature-card'>
                   <View className='feature-icon-box'>
                      <Text className='f-icon'>🛡</Text>
                   </View>
                   <View className='feature-text'>
                     <Text className='f-title'>工业级安全标准</Text>
                     <Text className='f-desc'>采用军工级加密芯片，保障您的数据隐私安全。无论是边缘计算还是云端同步，全程加密传输。</Text>
                   </View>
                </View>
                <View className='feature-card'>
                   <View className='feature-icon-box'>
                      <Text className='f-icon' style={{color: '#3b82f6'}}>👁</Text>
                   </View>
                   <View className='feature-text'>
                     <Text className='f-title' style={{color: '#3b82f6'}}>超清视觉感知</Text>
                     <Text className='f-desc'>搭载 4K 高清摄像头与 AI 视觉算法，实时捕捉每一个细节。支持人脸识别、物体检测等。</Text>
                   </View>
                </View>
             </>
           )}
        </View>

        {/* Detail Image */}
        {(product.display_detail_image || product.detail_image_url) && (
          <View className='detail-image-section'>
            <Image src={product.display_detail_image || product.detail_image_url} mode='widthFix' className='long-detail-img' />
          </View>
        )}
        
        <View className='footer-spacer' />
      </ScrollView>

      {/* Bottom Bar */}
      <View className='bottom-bar'>
        <View className='action-row'>
            <Button className='btn-add-cart' onClick={handleAddToCart}>
                <Text>加入购物车</Text>
            </Button>
            <Button className='btn-buy-now' onClick={buyNow}>
                <Text className='cart-icon'>🛒</Text>
                <Text>立即购买</Text>
            </Button>
        </View>
      </View>
    </View>
  )
}
