import { View, ScrollView, Text, Textarea } from '@tarojs/components'
import { useQuery, useMutation } from '@tanstack/react-query'
import React, { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { deliveryAddressClient, orderClient } from '@/api'
import { InferResponseType, InferRequestType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { useAuth } from '@/utils/auth'
import { useCart } from '@/contexts/CartContext'
import { Image } from '@/components/ui/image'
import './index.css'

type AddressResponse = InferResponseType<typeof deliveryAddressClient.$get, 200>
type Address = AddressResponse['data'][0]
type CreateOrderRequest = InferRequestType<typeof orderClient['create-order']['$post']>['json']

interface CheckoutItem {
  id: number
  name: string
  price: number
  image: string
  quantity: number
}

export default function OrderSubmitPage() {
  const { user } = useAuth()
  const { clearCart } = useCart()
  const [selectedAddress, setSelectedAddress] = useState<Address | null>(null)
  const [orderItems, setOrderItems] = useState<CheckoutItem[]>([])
  const [totalAmount, setTotalAmount] = useState(0)
  const [remark, setRemark] = useState("")
  const [isUserSelected, setIsUserSelected] = useState(false) 

  // 获取地址列表
  const { data: addresses } = useQuery({
    queryKey: ['delivery-addresses', user?.id],
    queryFn: async () => {
      const response = await deliveryAddressClient.$get({
        query: {
          page: 1,
          pageSize: 100,
          filters: JSON.stringify({ userId: user?.id })
        }
      })
      if (response.status !== 200) {
        throw new Error('获取地址失败')
      }
      return response.json()
    },
    enabled: !!user?.id,
  })

  // 创建订单
  const createOrderMutation = useMutation({
    mutationFn: async () => {
      if (!selectedAddress || orderItems.length === 0) {
        throw new Error('请完善订单信息')
      }

      const orderData: CreateOrderRequest = {
        addressId: selectedAddress.id,
        productOwn: '自营',
        consumeFrom: '积分兑换',
        products: orderItems.map(item => ({
          id: item.id,
          num: item.quantity
        })),
        remark: remark || undefined // 可选字段，如果为空则不传
      }

      const response = await orderClient['create-order']['$post']({ json: orderData })
      if (response.status !== 201) {
        throw new Error('创建订单失败')
      }
      return response.json()
    },
    onSuccess: (data) => {
      // 清空购物车
      clearCart()
      
      Taro.showToast({
        title: '订单创建成功',
        icon: 'success'
      })
      
      // 跳转到支付页面
      Taro.redirectTo({
        url: `/pages/payment/index?orderId=${data.orderId}&amount=${totalAmount}`
      })
    },
    onError: (error) => {
      Taro.showToast({
        title: error.message || '创建订单失败',
        icon: 'none'
      })
    }
  })

  // 页面显示时检查是否有新选择的地址
  // useEffect(() => {
  //   const handlePageShow = () => {
  //     console.log('pageShow 事件触发')
  //     const storedAddress = Taro.getStorageSync('selectedAddressData')
  //     console.log("get selectedAddressData:", storedAddress);
  //     if (storedAddress) {
  //       setSelectedAddress(storedAddress)
  //       setIsUserSelected(true) // 标记为用户手动选择
  //       Taro.removeStorageSync('selectedAddressData')
  //       console.log("selectedAddress00:", storedAddress)
  //     }
  //   }

  //   // 监听页面显示事件
  //   Taro.eventCenter.on('pageShow', handlePageShow)

  //   // 组件挂载时也检查一次存储
  //   const initialAddress = Taro.getStorageSync('selectedAddressData')
  //   if (initialAddress) {
  //     setSelectedAddress(initialAddress)
  //     setIsUserSelected(true) // 标记为用户手动选择
  //     Taro.removeStorageSync('selectedAddressData')
  //   }

  //   return () => {
  //     Taro.eventCenter.off('pageShow', handlePageShow)
  //   }
  // }, [])

  // 页面加载时获取订单数据 - 只执行一次
  useEffect(() => {
    // 从立即购买获取数据
    const buyNowData = Taro.getStorageSync('buyNow')
    const checkoutData = Taro.getStorageSync('checkoutItems')
    // const cartData = Taro.getStorageSync('mini_cart')

    // console.log("buyNowData",buyNowData)
    // console.log("checkoutItems",checkoutData)
    // console.log("mini_cart",cartData)

    if (buyNowData && buyNowData.goods) {
      // 使用立即购买的商品数据
      const goods = buyNowData.goods
      setOrderItems([{
        id: goods.id,
        name: goods.name,
        price: goods.price,
        image: goods.image,
        quantity: goods.quantity
      }])
      setTotalAmount(buyNowData.totalAmount)
      // 清除立即购买数据，避免下次进入时重复使用
      
    }
    else if(checkoutData&&checkoutData.items)
    {
      // 从购物车获取数据
        setOrderItems(checkoutData.items)
        setTotalAmount(checkoutData.totalAmount)
    }
  //   else if (cartData && cartData.items) {
  //       // 使用购物车数据
  //       const items = cartData.items
  //       const total = items.reduce((sum: number, item: CheckoutItem) =>
  //         sum + (item.price * item.quantity), 0)
  //       setOrderItems(items)
  //       setTotalAmount(total)

  //       // Taro.removeStorageSync('mini_cart')
  // }
    else
    {
       // 如果没有立即购买数据，清空订单项
       setOrderItems([])
       setTotalAmount(0)
     }
  }, []) // 空依赖数组，确保只执行一次

  // 设置默认地址 - 只在页面初始加载且没有手动选择地址时设置
  useEffect(() => {
    // 只在页面首次加载且没有手动选择地址且不是用户手动选择时设置默认地址
    if (addresses?.data) {
      const defaultAddress = addresses.data.find(addr => addr.isDefault === 1)
      setSelectedAddress(defaultAddress || addresses.data[0] || null)
    }
  }, [addresses]) // 只在地址数据变化时设置默认地址，且只在没有选择地址且不是用户手动选择时


  // 选择地址
  const handleSelectAddress = () => {
    Taro.navigateTo({
      url: '/pages/address-manage/index'
    })
  }

  // 处理备注输入
  const handleRemarkChange = (e: any) => {
    setRemark(e.detail.value)
  }

  // 提交订单
  const handleSubmitOrder = () => {
    if (!selectedAddress) {
      Taro.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }

    createOrderMutation.mutate()
  }

 // console.log("渲染时 selectedAddress:", selectedAddress)

  return (
    <View className="order-sure">
      <Navbar
        title="确认订单"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />

      <ScrollView
        className="h-screen pt-12"
        scrollY={true}
        scrollWithAnimation={true}
        enableFlex={true}
      >
        <View className="content-wrapper">
        {/* 收货地址区域 */}
        <View className="address-card">
          {selectedAddress ? (
            <View className="order-address" onClick={handleSelectAddress}>
              <View className="address-content">

              {/* {selectedAddress.province?.name || ''}
                  {selectedAddress.city?.name || ''}
                  {selectedAddress.district?.name || ''}
                  {selectedAddress.town?.name || ''} */}

                <Text className="detail">
                  {selectedAddress.address}
                </Text>
                <View className="info">
                  {selectedAddress.isDefault === 1 && (
                    <Text className="address-tag">默认</Text>
                  )}
                  <Text>
                    {selectedAddress.name} {selectedAddress.phone}
                  </Text>
                </View>
              </View>
              <View className="i-heroicons-chevron-right-20-solid address__right" />
            </View>
          ) : (
            <View className="order-address" onClick={handleSelectAddress}>
              <View className="address-content">
                <Text className="detail">请选择收货地址</Text>
              </View>
              <View className="i-heroicons-chevron-right-20-solid address__right" />
            </View>
          )}
          <View className="top-line" />
        </View>

        {/* 商品列表区域 */}
        <View className="order-wrapper">
          {orderItems.map((item) => (
            <View key={item.id} className="goods-wrapper">
              <Image
                src={item.image}
                className="goods-image"
                mode="aspectFill"
              />

              <View className="goods-content">
                <Text className="goods-title">{item.name}</Text>
                <Text className="text-gray-600">规格：默认</Text>
              </View>

              <View className="goods-right">
                <Text className="goods-price">¥{item.price.toFixed(2)}</Text>
                <Text className="goods-num">x{item.quantity}</Text>
              </View>
            </View>
          ))}
        </View>

        {/* 支付详情区域 */}
        <View className="pay-detail">
          <View className="pay-item">
            <Text>商品总额</Text>
            <Text className="pay-item__right font-bold">¥{totalAmount.toFixed(2)}</Text>
          </View>
          <View className="pay-item">
            <Text>运费</Text>
            <Text className="pay-item__right">¥0.00</Text>
          </View>
        </View>

        {/* 金额区域 */}
        <View className="amount-wrapper">
          <View className="pay-amount">
            <Text className="order-num">共{orderItems.length}件</Text>
            <Text>小计</Text>
            <Text className="total-price">¥{totalAmount.toFixed(2)}</Text>
          </View>
        </View>


        {/* 备注区域 */}
        <View className="remark-section">
          <View className="remark-header">
            <Text className="remark-title">订单备注</Text>
            <Text className="remark-tip">（选填，请填写与订单相关的备注信息）</Text>
          </View>
          <Textarea
            className="remark-textarea"
            placeholder="请输入订单备注信息..."
            value={remark}
            onInput={handleRemarkChange}
            maxlength={255}
            showConfirmBar={true}
          />
          <View className="remark-counter">
            <Text className="remark-count">{remark.length}/255</Text>
          </View>
        </View>


        </View>
      </ScrollView>

      {/* 底部提交栏 */}
      <View className="wx-pay-cover">
        <View className="wx-pay">
          <Text className="price">¥{totalAmount.toFixed(2)}</Text>
          <View
            className={`submit-btn ${selectedAddress ? '' : 'btn-gray'}`}
            onClick={selectedAddress ? handleSubmitOrder : undefined}
          >
            {createOrderMutation.isPending ? '提交中...' : '提交订单'}
          </View>
        </View>
      </View>
    </View>
  )
}