import React from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useAddress } from '@/hooks/useAddress'
import AddressCard from '@/components/business/AddressCard'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '收货地址',
})

const AddressListPage: React.FC = () => {
  const { addresses, loading, loadAddresses, deleteAddress, setDefault } = useAddress()

  // 判断是否从结算页进来（选择地址模式）
  const { from, select } = Taro.getCurrentInstance().router?.params || {}
  const isSelectMode = select === '1' || from === 'checkout'

  useDidShow(() => {
    loadAddresses()
  })

  const handleDelete = (id: number) => {
    Taro.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          const success = await deleteAddress(id)
          if (success) {
            Taro.showToast({ title: '删除成功', icon: 'success' })
          } else {
            Taro.showToast({ title: '删除失败', icon: 'none' })
          }
        }
      }
    })
  }

  const handleEdit = (id: number) => {
    Taro.navigateTo({ url: `/pages/user/address-edit?id=${id}` })
  }

  const handleAdd = () => {
    Taro.navigateTo({ url: '/pages/user/address-edit' })
  }

  /** 选择地址：设为默认后返回上一页（结算页） */
  const handleSelect = async (id: number) => {
    if (!isSelectMode) return

    // 选择模式：设为默认地址后返回
    const addr = addresses.find(a => a.id === id)
    if (!addr) return

    if (!addr.isDefault) {
      await setDefault(id)
    }

    // 通知结算页刷新地址
    setTimeout(() => {
      Taro.navigateBack()
    }, 300)
  }

  return (
    <View className="min-h-screen bg-gray-50 flex flex-col">
      {/* 地址列表区域 */}
      <ScrollView scrollY className="flex-1">
        <View className="p-3 pb-20">
          {loading ? (
            <View className="flex items-center justify-center py-20">
              <Text className="text-gray-400 text-sm">加载中...</Text>
            </View>
          ) : addresses.length === 0 ? (
            <View className="pt-20">
              <EmptyState
                text="暂无收货地址"
                actionText="添加地址"
                onAction={handleAdd}
              />
            </View>
          ) : (
            addresses.map(addr => (
              <AddressCard
                key={addr.id}
                address={addr}
                selectMode={isSelectMode}
                selected={!!addr.isDefault}
                onClick={() => isSelectMode ? handleSelect(addr.id!) : handleEdit(addr.id!)}
                showActions
                onEdit={() => handleEdit(addr.id!)}
                onDelete={() => handleDelete(addr.id!)}
                onDefault={() => setDefault(addr.id!)}
              />
            ))
          )}
        </View>
      </ScrollView>

      {/* 底部固定按钮 */}
      <View className="bg-white border-t border-gray-200 px-4 py-3" style={{ paddingBottom: '20px' }}>
        <View
          className="py-3 rounded-full text-center"
          style={{ backgroundColor: '#0e932e' }}
          onClick={handleAdd}
        >
          <Text className="text-white font-medium text-sm">新增收货地址</Text>
        </View>
      </View>
    </View>
  )
}

export default AddressListPage
