import { View, ScrollView, Text } from '@tarojs/components'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useRef } from 'react'
import Taro from '@tarojs/taro'
import { deliveryAddressClient } from '@/api'
import { InferResponseType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import { useAuth } from '@/utils/auth'
import './index.css'

type AddressResponse = InferResponseType<typeof deliveryAddressClient.$get, 200>
type Address = AddressResponse['data'][0]

export default function AddressManagePage() {
  const { user } = useAuth()
  const queryClient = useQueryClient()
  const [swipeStates, setSwipeStates] = useState<Record<number, boolean>>({})
  const [touchStartX, setTouchStartX] = useState<number | null>(null)
  const [currentSwipeId, setCurrentSwipeId] = useState<number | null>(null)

  // 获取地址列表
  const { data: addresses, isLoading } = 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,
    staleTime: 5 * 60 * 1000,
  })

  // 删除地址
  const deleteAddressMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await deliveryAddressClient[':id'].$delete({
        param: { id }
      })
      if (response.status !== 204) {
        throw new Error('删除地址失败')
      }
      // 204 响应没有内容，不需要调用 response.json()
      return null
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['delivery-addresses'] })
      Taro.showToast({
        title: '删除成功',
        icon: 'success'
      })
    },
    onError: (error) => {
      Taro.showToast({
        title: error.message || '删除失败',
        icon: 'none'
      })
    }
  })

  // 设置默认地址
  const setDefaultMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await deliveryAddressClient[':id']['$put']({
        param: { id },
        json: { isDefault: 1 }
      })
      if (response.status !== 200) {
        throw new Error('设置默认地址失败')
      }
      return response.json()
    },
    onMutate: async (id: number) => {
      // 取消之前的查询，避免冲突
      await queryClient.cancelQueries({ queryKey: ['delivery-addresses', user?.id] })

      // 保存之前的快照
      const previousAddresses = queryClient.getQueryData(['delivery-addresses', user?.id])

      // 乐观更新：将所有地址设为非默认，将指定地址设为默认
      queryClient.setQueryData(['delivery-addresses', user?.id], (old: any) => {
        if (!old?.data) return old

        return {
          ...old,
          data: old.data.map((address: Address) => ({
            ...address,
            isDefault: address.id === id ? 1 : 0
          }))
        }
      })

      return { previousAddresses }
    },
    onError: (error, id, context) => {
      // 出错时回滚到之前的状态
      if (context?.previousAddresses) {
        queryClient.setQueryData(['delivery-addresses', user?.id], context.previousAddresses)
      }
      Taro.showToast({
        title: error.message || '设置失败',
        icon: 'none'
      })
    },
    onSuccess: () => {
      // 成功后重新获取数据确保一致性
      queryClient.invalidateQueries({ queryKey: ['delivery-addresses'] })
      Taro.showToast({
        title: '设置成功',
        icon: 'success'
      })
      
      Taro.navigateTo({
        url: '/pages/order-submit/index'
      })
  
    }
  })

  // 跳转到添加地址页面
  const handleAddAddress = () => {
    Taro.navigateTo({
      url: '/pages/address-edit/index'
    })
  }

  // 跳转到编辑地址页面
  const handleEditAddress = (address: Address) => {
    Taro.navigateTo({
      url: `/pages/address-edit/index?id=${address.id}`
    })
  }

  // 选择地址并返回
  const handleSelectAddress = (address: Address) => {
    closeAllSwipes()
    Taro.setStorageSync('selectedAddressData', address)
    //console.log("selectedAddressData:", address)
    Taro.navigateBack()
     
  }

  // 检查是否是选择模式
  const isSelectMode = () => {
    const pages = Taro.getCurrentPages()
    const prevPage = pages[pages.length - 2]
    return prevPage && prevPage.route === 'pages/order-submit/index'
  }


  // 打开侧滑
  const openSwipe = (id: number) => {
    setSwipeStates({ [id]: true })
    setCurrentSwipeId(id)
  }

  // 关闭所有侧滑
  const closeAllSwipes = () => {
    setSwipeStates({})
    setCurrentSwipeId(null)
    setTouchStartX(null)
  }

  // 触摸开始
  const handleTouchStart = (e: any, id: number) => {
    setTouchStartX(e.touches[0].clientX)
    setCurrentSwipeId(id)
  }

  // 触摸移动
  const handleTouchMove = (e: any, id: number) => {
    if (touchStartX === null) return

    const touchCurrentX = e.touches[0].clientX
    const diffX = touchStartX - touchCurrentX

    // 向左滑动超过50px时打开侧滑
    if (diffX > 50) {
      openSwipe(id)
    }
    // 向右滑动超过30px时关闭侧滑
    else if (diffX < -30 && currentSwipeId === id) {
      closeAllSwipes()
    }
  }

  // 触摸结束
  const handleTouchEnd = () => {
    setTouchStartX(null)
  }

  // 删除地址
  const handleDeleteAddress = (id: number) => {
    console.log("id:",id)
    closeAllSwipes()
    Taro.showModal({
      title: '删除地址',
      content: '确定要删除这个收货地址吗？',
      success: (res) => {
        console.log("res",res)
        if (res.confirm) {
          deleteAddressMutation.mutate(id)
        }
      }
    })
  }

  return (
    <View className="address-container">
      <Navbar
        title="收货地址"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />

      <ScrollView className="address-scroll-view">
        {isLoading ? (
          <View className="loading-container">
            <View className="i-heroicons-arrow-path-20-solid animate-spin loading-icon" />
          </View>
        ) : (
          <>
            <View className="address-list">
              {addresses?.data?.map((address) => (
                <View key={address.id} className="address-item">
                  {/* 侧滑删除区域 */}
                  <View
                    className="swipe-cell"
                    onClick={() => closeAllSwipes()}
                    onTouchStart={(e) => handleTouchStart(e, address.id)}
                    onTouchMove={(e) => handleTouchMove(e, address.id)}
                    onTouchEnd={handleTouchEnd}
                  >
                    <View
                      className="swipe-content"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <View className="address-content">
                        <View className="address-header">
                          <Text className="address-name">{address.name}</Text>
                          <Text className="address-phone">
                            {address.phone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}
                          </Text>
                          {address.isDefault === 1 && (
                            <Text className="default-tag">默认</Text>
                          )}
                        </View>

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

                        <Text className="address-detail">
                          
                          {address.address}
                        </Text>

                        <View className="address-actions">
                          {
                          // isSelectMode() ? (
                          //   <Button
                          //     size="sm"
                          //     className="select-btn"
                          //     onClick={() => handleSelectAddress(address)}
                          //   >
                          //     选择
                          //   </Button>
                          // ) : 
                          
                         // (
                            <>
                              <View className="action-buttons">
                                {address.isDefault !== 1 && (
                                  <Button
                                    size="sm"
                                    variant="ghost"
                                    className="set-default-btn"
                                    onClick={() => setDefaultMutation.mutate(address.id)}
                                  >
                                    设为默认
                                  </Button>
                                )}

                                <Button
                                  size="sm"
                                  variant="ghost"
                                  className="edit-btn"
                                  onClick={() => handleEditAddress(address)}
                                >
                                  编辑
                                </Button>
                              </View>

                              {/* <Button
                                size="sm"
                                className="select-btn"
                                onClick={() => handleSelectAddress(address)}
                              >
                                选择
                              </Button> */}

                            </>
                         // )
                          }
                        </View>
                      </View>
                    </View>

                    <View
                      className={`swipe-actions ${swipeStates[address.id] ? 'swipe-open' : ''}`}
                      onClick={(e) => e.stopPropagation()}
                    >
                      <Button
                        className="delete-btn"
                        onClick={() => handleDeleteAddress(address.id)}
                      >
                        删除
                      </Button>
                    </View>
                  </View>
                </View>
              ))}
            </View>

            {addresses?.data?.length === 0 && (
              <View className="no-address">
                <View className="no-address-icon" />
                <Text className="no-address-text">暂无收货地址</Text>
              </View>
            )}
          </>
        )}
      </ScrollView>

      {/* 底部固定添加按钮 */}
      <View className="bottom-fixed">
        <Button
          className={`address-btn ${addresses?.data?.length >= 20 ? 'disabled' : ''}`}
          onClick={handleAddAddress}
          disabled={addresses?.data?.length >= 20}
        >
          添加新地址
        </Button>
        {addresses?.data?.length >= 20 && (
          <Text className="limit-tip">最多可添加20个收货地址</Text>
        )}
      </View>
    </View>
  )
}