import { useState, useCallback } from 'react'
import {
  listShopUserAddress,
  getShopUserAddress,
  addShopUserAddress,
  updateShopUserAddress,
  removeShopUserAddress,
  setDefaultAddress,
} from '@/api/shop/shopUserAddress'
import type { ShopUserAddress } from '@/api/shop/shopUserAddress/model'

interface UseAddressReturn {
  addresses: ShopUserAddress[]
  loading: boolean
  defaultAddress: ShopUserAddress | null
  loadAddresses: () => Promise<void>
  getAddress: (id: number) => Promise<ShopUserAddress | null>
  addAddress: (data: Partial<ShopUserAddress>) => Promise<boolean>
  updateAddress: (data: ShopUserAddress) => Promise<boolean>
  deleteAddress: (id: number) => Promise<boolean>
  setDefault: (id: number) => Promise<boolean>
}

export function useAddress(): UseAddressReturn {
  const [addresses, setAddresses] = useState<ShopUserAddress[]>([])
  const [loading, setLoading] = useState(false)

  const loadAddresses = useCallback(async () => {
    setLoading(true)
    try {
      const list = await listShopUserAddress()
      const actualList = Array.isArray(list) ? list : (list as any)?.data || []
      setAddresses(actualList)
    } catch (error) {
      console.error('Load addresses error:', error)
      setAddresses([])
    } finally {
      setLoading(false)
    }
  }, [])

  /** 根据 ID 获取单个地址 */
  const getAddress = useCallback(async (id: number): Promise<ShopUserAddress | null> => {
    try {
      return await getShopUserAddress(id)
    } catch {
      return null
    }
  }, [])

  const addAddress = useCallback(async (data: Partial<ShopUserAddress>): Promise<boolean> => {
    try {
      await addShopUserAddress(data as any)
      await loadAddresses()
      return true
    } catch {
      return false
    }
  }, [loadAddresses])

  const updateAddress = useCallback(async (data: ShopUserAddress): Promise<boolean> => {
    try {
      await updateShopUserAddress(data)
      await loadAddresses()
      return true
    } catch {
      return false
    }
  }, [loadAddresses])

  const deleteAddress = useCallback(async (id: number): Promise<boolean> => {
    try {
      await removeShopUserAddress(id)
      setAddresses(prev => prev.filter(a => a.id !== id))
      return true
    } catch {
      return false
    }
  }, [])

  const setDefault = useCallback(async (id: number): Promise<boolean> => {
    try {
      await setDefaultAddress(id)
      await loadAddresses()
      return true
    } catch {
      return false
    }
  }, [loadAddresses])

  const defaultAddress = addresses.find(a => a.isDefault) || addresses[0] || null

  return { addresses, loading, defaultAddress, loadAddresses, getAddress, addAddress, updateAddress, deleteAddress, setDefault }
}
