import { View, Text, Image, ScrollView, Button } from '@tarojs/components'
import Taro, { useRouter, useLoad } from '@tarojs/taro'
import { useState, useMemo } from 'react'
import { getConfigDetail, createOrder, getVBCourseDetail } from '../../api'
import { getSelectedItems, removeItem } from '../../utils/cart'
import './checkout.scss'

export default function Checkout() {
  const router = useRouter()
  const params = router.params
  const [items, setItems] = useState<any[]>([])
  const [address, setAddress] = useState<any>(null)
  const [deliveryType, setDeliveryType] = useState<'delivery' | 'pickup'>('delivery')
  const [userAddress, setUserAddress] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  const PICKUP_ADDRESS = {
    userName: '云南量迹科技有限公司',
    telNumber: '18585164448',
    provinceName: '云南省',
    cityName: '昆明市',
    countyName: '西山区',
    detailInfo: '永昌街道办事处云纺国际商厦 B 座 1406 号'
  }

  useLoad(async () => {
    if (params.from === 'cart') {
      const cartItems = getSelectedItems()
      if (cartItems.length === 0) {
        Taro.navigateBack()
        return
      }
      setItems(cartItems)
      setLoading(false)
    } else if (params.id) {
      try {
        let res: any = null
        if (params.type === 'course') {
            res = await getVBCourseDetail(Number(params.id))
            setItems([{
                id: res.id,
                name: res.title,
                price: res.price,
                image: res.cover_image_url || res.detail_image_url,
                quantity: 1,
                description: res.description
            }])
        } else {
            res = await getConfigDetail(params.id)
            setItems([{
                id: res.id,
                name: res.name,
                price: res.price,
                image: res.static_image_url || res.detail_image_url,
                quantity: Number(params.quantity) || 1,
                description: res.description
            }])
        }
      } catch (err) {
        console.error(err)
        Taro.showToast({ title: '商品加载失败', icon: 'none' })
      } finally {
        setLoading(false)
      }
    }
  })

  const chooseAddress = async () => {
    if (deliveryType === 'pickup') return
    try {
      const res = await Taro.chooseAddress()
      setAddress(res)
      setUserAddress(res)
    } catch (err) {
      console.error(err)
      // User cancelled or auth denied
    }
  }

  const handleTypeChange = (type: 'delivery' | 'pickup') => {
    if (type === deliveryType) return
    setDeliveryType(type)
    if (type === 'pickup') {
        setAddress(PICKUP_ADDRESS)
    } else {
        setAddress(userAddress)
    }
  }

  const totalPrice = useMemo(() => {
    return items.reduce((sum, item) => sum + item.price * item.quantity, 0)
  }, [items])

  const submitOrder = async () => {
    if (!address) {
      Taro.showToast({ title: '请选择收货地址', icon: 'none' })
      return
    }

    Taro.showLoading({ title: '提交中...' })

    try {
      const orderPromises = items.map(item => {
        const type = params.type || 'config'
        const orderData: any = {
            quantity: item.quantity,
            customer_name: address.userName,
            phone_number: address.telNumber,
            shipping_address: `${address.provinceName}${address.cityName}${address.countyName}${address.detailInfo}`,
            ref_code: Taro.getStorageSync('ref_code') || ''
        }
        
        if (type === 'course') {
            orderData.course = item.id
        } else {
            orderData.config = item.id
        }
        
        return createOrder(orderData)
      })

      const results = await Promise.all(orderPromises)
      
      // If from cart, remove bought items
      if (params.from === 'cart') {
          items.forEach(item => removeItem(item.id))
      }

      Taro.hideLoading()
      
      if (results.length === 1) {
          // Single order, go to payment
          const orderId = results[0].id
          Taro.redirectTo({
              url: `/pages/order/payment?id=${orderId}`
          })
      } else {
          // Multiple orders
          Taro.showModal({
              title: '下单成功',
              content: `成功创建 ${results.length} 个订单，请前往订单列表支付`,
              showCancel: false,
              confirmText: '去支付',
              success: () => {
                  Taro.redirectTo({ url: '/pages/order/list' })
              }
          })
      }

    } catch (err) {
      Taro.hideLoading()
      console.error(err)
      Taro.showToast({ title: '下单失败', icon: 'none' })
    }
  }

  if (loading) return <View className='page-container'><View className='section'><Text>Loading...</Text></View></View>

  return (
    <View className='page-container'>
      <ScrollView scrollY style={{height: 'calc(100vh - 120px)'}}>
        {/* Delivery Type Section */}
        <View className='section delivery-type-section'>
            <View 
                className={`type-item ${deliveryType === 'delivery' ? 'active' : ''}`}
                onClick={() => handleTypeChange('delivery')}
            >
                快递配送
            </View>
            <View 
                className={`type-item ${deliveryType === 'pickup' ? 'active' : ''}`}
                onClick={() => handleTypeChange('pickup')}
            >
                门店自提
            </View>
        </View>

        {/* Address Section */}
        <View className='section address-section' onClick={chooseAddress}>
            {address ? (
                <View className='address-info'>
                    <View className='user-info'>
                        <Text>{address.userName}</Text>
                        <Text className='phone'>{address.telNumber}</Text>
                    </View>
                    <View className='address-text'>
                        {address.provinceName}{address.cityName}{address.countyName}{address.detailInfo}
                    </View>
                </View>
            ) : (
                <View className='address-info'>
                    <Text className='placeholder'>+ 添加收货地址</Text>
                </View>
            )}
            {deliveryType === 'delivery' && <Text className='arrow'>›</Text>}
        </View>

        {/* Products Section */}
        <View className='section product-section'>
            <Text className='section-title'>商品信息</Text>
            {items.map((item, idx) => (
                <View key={idx} className='product-item'>
                    <Image src={item.image} className='p-img' mode='aspectFill' />
                    <View className='p-info'>
                        <Text className='p-name'>{item.name}</Text>
                        <Text className='p-desc'>{item.description}</Text>
                        <View className='p-meta'>
                            <Text className='p-price'>¥{item.price}</Text>
                            <Text className='p-qty'>x{item.quantity}</Text>
                        </View>
                    </View>
                </View>
            ))}
        </View>

        {/* Summary Section */}
        <View className='section summary-section'>
            <View className='row'>
                <Text>商品总价</Text>
                <Text>¥{totalPrice}</Text>
            </View>
            <View className='row'>
                <Text>运费</Text>
                <Text>¥0</Text>
            </View>
            <View className='row total'>
                <Text>合计</Text>
                <Text className='price'>¥{totalPrice}</Text>
            </View>
        </View>
      </ScrollView>

      {/* Bottom Bar */}
      <View className='bottom-bar'>
        <Text className='total-label'>共{items.length}件</Text>
        <Text className='total-price'>¥{totalPrice}</Text>
        <Button className='btn-submit' onClick={submitOrder}>提交订单</Button>
      </View>
    </View>
  )
}
