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

type AddressResponse = InferResponseType<typeof deliveryAddressClient.$get, 200>
type Address = AddressResponse['data'][0]
type CreateAddressRequest = InferRequestType<typeof deliveryAddressClient.$post>['json']
type UpdateAddressRequest = InferRequestType<typeof deliveryAddressClient[':id']['$put']>['json']

export default function AddressManagePage() {
  const { user } = useAuth()
  const queryClient = useQueryClient()
  const [selectedAddressId, setSelectedAddressId] = 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('删除地址失败')
      }
      return response.json()
    },
    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()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['delivery-addresses'] })
      Taro.showToast({
        title: '设置成功',
        icon: 'success'
      })
    }
  })

  // 跳转到添加地址页面
  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) => {
    // 检查是否是选择模式
    const pages = Taro.getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    if (prevPage && prevPage.route === 'pages/order-submit/index') {
      // 返回订单页面
      prevPage.setData({
        selectedAddress: address
      })
      Taro.navigateBack()
    }
  }

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

  return (
    <View className="min-h-screen bg-gray-50 flex flex-col">
      <Navbar
        title="收货地址"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />
      
      <ScrollView className="flex-1">
        <View className="px-4 py-4">
          {isLoading ? (
            <View className="flex justify-center py-10">
              <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
            </View>
          ) : (
            <>
              {addresses?.data?.map((address) => (
                <Card key={address.id} className="mb-4">
                  <View className="p-4">
                    <View className="flex items-start justify-between mb-2">
                      <View className="flex-1">
                        <View className="flex items-center mb-1">
                          <Text className="font-medium text-gray-900 mr-2">
                            {address.name}
                          </Text>
                          <Text className="text-sm text-gray-600">
                            {address.phone}
                          </Text>
                          {address.isDefault === 1 && (
                            <Text className="ml-2 px-2 py-1 bg-red-100 text-red-600 text-xs rounded">
                              默认
                            </Text>
                          )}
                        </View>
                        
                        <Text className="text-sm text-gray-700">
                          {address.province?.name || ''} 
                          {address.city?.name || ''} 
                          {address.district?.name || ''} 
                          {address.town?.name || ''} 
                          {address.address}
                        </Text>
                      </View>
                    </View>
                    
                    <View className="flex items-center justify-between pt-3 border-t border-gray-100">
                      <View className="flex space-x-4">
                        {address.isDefault !== 1 && (
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setDefaultMutation.mutate(address.id)}
                          >
                            设为默认
                          </Button>
                        )}
                        
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleEditAddress(address)}
                        >
                          编辑
                        </Button>
                        
                        <Button
                          size="sm"
                          variant="ghost"
                          className="text-red-500"
                          onClick={() => handleDeleteAddress(address.id)}
                        >
                          删除
                        </Button>
                      </View>
                      
                      <Button
                        size="sm"
                        onClick={() => handleSelectAddress(address)}
                      >
                        选择
                      </Button>
                    </View>
                  </View>
                </Card>
              ))}
              
              {addresses?.data?.length === 0 && (
                <View className="flex flex-col items-center py-20">
                  <View className="i-heroicons-map-pin-20-solid w-16 h-16 text-gray-300 mb-4" />
                  <Text className="text-gray-500 mb-4">暂无收货地址</Text>
                </View>
              )}
            </>
          )}
        </View>
      </ScrollView>

      {/* 底部添加按钮 */}
      <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-3">
        <Button 
          className="w-full"
          onClick={handleAddAddress}
        >
          添加新地址
        </Button>
      </View>
    </View>
  )
}