import { useState, useEffect, useRef } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { trpc } from '#/lib/trpc-client'
import { useAuth } from '#/lib/auth-context'
import { useAddressStore } from '#/lib/stores'

interface CheckoutAddressSelectorProps {
  onAddressSelect?: (addressId: number) => void
}

export function useCheckoutAddress({ onAddressSelect }: CheckoutAddressSelectorProps = {}) {
  const { isAuthenticated } = useAuth()
  const queryClient = useQueryClient()
  const { selectedAddressId, setSelectedAddressId } = useAddressStore()
  const [showAddAddress, setShowAddAddress] = useState(false)
  const [editingAddress, setEditingAddress] = useState<any>(null)

  const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(
    undefined,
    { enabled: isAuthenticated }
  )

  const addresses = addressesData?.data || []

  // Sort addresses with selected first, then default, then others
  const sortedAddresses = (() => {
    return [...addresses].sort((a, b) => {
      // Selected address comes first
      if (selectedAddressId === a.id && selectedAddressId !== b.id) return -1
      if (selectedAddressId === b.id && selectedAddressId !== a.id) return 1

      // Then default address (if not already selected)
      if (a.isDefault && !b.isDefault) return -1
      if (!a.isDefault && b.isDefault) return 1

      // Maintain stable sort by id for other addresses
      return a.id - b.id
    })
  })()

  // Auto-select default address when addresses are loaded and none is selected
  useEffect(() => {
    if (sortedAddresses.length > 0 && selectedAddressId === null) {
      const defaultAddress = sortedAddresses.find((addr: any) => addr.isDefault)
      if (defaultAddress) {
        setSelectedAddressId(defaultAddress.id)
        onAddressSelect?.(defaultAddress.id)
      }
    }
  }, [sortedAddresses.length, selectedAddressId])

  const handleAddressSelect = (addressId: number) => {
    setSelectedAddressId(addressId)
    onAddressSelect?.(addressId)
  }

  const handleAddSuccess = (addressId?: number) => {
    setShowAddAddress(false)
    setEditingAddress(null)
    if (addressId) {
      setSelectedAddressId(addressId)
      onAddressSelect?.(addressId)
    }
    queryClient.invalidateQueries({ queryKey: ['user.address.getUserAddresses'] })
  }

  const handleEditAddress = (address: any) => {
    setEditingAddress(address)
    setShowAddAddress(true)
  }

  return {
    addresses,
    sortedAddresses,
    selectedAddressId,
    showAddAddress,
    setShowAddAddress,
    editingAddress,
    handleAddressSelect,
    handleAddSuccess,
    handleEditAddress,
  }
}
