freshyo/apps/web-ui/src/routes/me.addresses.tsx
2026-10-13 18:11:25 +05:30

264 lines
9.1 KiB
TypeScript

import { createFileRoute } from '@tanstack/react-router'
import { trpc } from '../lib/trpc-client'
import { useState } from 'react'
import { MeScreenHeader } from '../components/me/MeScreenHeader'
import { AddressForm } from '../components/AddressForm'
import { BottomDialog } from 'web-components'
import type { UserAddress } from '@packages/shared'
import { MapPin, Plus, AlertTriangle } from 'lucide-react'
export const Route = createFileRoute('/me/addresses')({ component: AddressesPage })
// Address view — required core of the shared UserAddress + optional geo fields
type Address = Pick<
UserAddress,
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault'
> & {
latitude?: number | null
longitude?: number | null
googleMapsUrl?: string | null
}
const formatAddress = (addr: Address) => {
return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state}`
}
function AddressCard({
address,
onEdit,
onDelete,
onSetDefault,
isDeleting,
}: {
address: Address
onEdit: (address: Address) => void
onDelete: (id: number) => void
onSetDefault: (id: number) => void
isDeleting?: boolean
}) {
return (
<div className="mb-3 rounded-lg border border-gray-100 bg-white p-4 shadow-sm">
<div className="mb-2 flex flex-row items-start justify-between">
<div className="flex-1">
<div className="mb-1 flex flex-row items-center">
<p className="mr-2 text-lg font-semibold text-gray-800">{address.name}</p>
{address.isDefault && (
<span className="rounded-full bg-green-100 px-2 py-1">
<p className="text-xs font-medium text-green-700">Default</p>
</span>
)}
</div>
<p className="mb-1 text-sm text-gray-600">📞 {address.phone}</p>
<p className="text-sm text-gray-700">📍 {formatAddress(address)}</p>
</div>
</div>
<div className="mt-3 flex flex-row justify-end">
{!address.isDefault && (
<button
onClick={() => onSetDefault(address.id)}
className="mr-2 rounded bg-gray-500 px-3 py-2 transition-colors hover:bg-gray-600"
>
<p className="text-xs font-medium text-white">Set Default</p>
</button>
)}
<button
onClick={() => onEdit(address)}
className="mr-2 rounded bg-blue-500 px-3 py-2 transition-colors hover:bg-blue-600"
>
<p className="text-xs font-medium text-white">Edit</p>
</button>
<button
onClick={() => onDelete(address.id)}
disabled={isDeleting}
className={`rounded bg-red-500 px-3 py-2 transition-colors hover:bg-red-600 ${
isDeleting ? 'opacity-50' : ''
}`}
>
<p className="text-xs font-medium text-white">
{isDeleting ? 'Deleting...' : 'Delete'}
</p>
</button>
</div>
</div>
)
}
function AddressesPage() {
const [modalVisible, setModalVisible] = useState(false)
const [editingAddress, setEditingAddress] = useState<Address | null>(null)
const [deletingId, setDeletingId] = useState<number | null>(null)
const { data, isLoading, error, refetch } = trpc.user.address.getUserAddresses.useQuery()
const addresses = (data?.data || []) as Address[]
const updateAddressMutation = trpc.user.address.updateAddress.useMutation()
const deleteAddressMutation = trpc.user.address.deleteAddress.useMutation()
const handleAddAddress = () => {
setEditingAddress(null)
setModalVisible(true)
}
const handleEditAddress = (address: Address) => {
setEditingAddress(address)
setModalVisible(true)
}
const handleDeleteAddress = (id: number) => {
const ok = window.confirm('Are you sure you want to delete this address?')
if (!ok) return
setDeletingId(id)
deleteAddressMutation.mutate(
{ id },
{
onSuccess: () => {
setDeletingId(null)
refetch()
alert('Address deleted successfully')
},
onError: (error: any) => {
setDeletingId(null)
alert(error.message || 'Failed to delete address')
},
}
)
}
const handleSetDefault = (id: number) => {
const addressToUpdate = addresses.find((addr) => addr.id === id)
if (!addressToUpdate) return
if (addressToUpdate.regionId == null) {
alert('This address has no region. Please edit it and choose a region first.')
return
}
updateAddressMutation.mutate(
{
id: addressToUpdate.id,
regionId: addressToUpdate.regionId,
name: addressToUpdate.name,
phone: addressToUpdate.phone,
addressLine1: addressToUpdate.addressLine1,
addressLine2: addressToUpdate.addressLine2 || undefined,
city: addressToUpdate.city,
state: addressToUpdate.state,
isDefault: true,
// Keep the stored coordinates so the bound is not re-derived from a fallback.
latitude: addressToUpdate.latitude ?? undefined,
longitude: addressToUpdate.longitude ?? undefined,
},
{
onSuccess: () => {
refetch()
alert('Default address updated')
},
onError: (error: any) => {
alert(error.message || 'Failed to update default address')
},
}
)
}
const handleAddressSubmit = () => {
setModalVisible(false)
setEditingAddress(null)
refetch()
}
return (
<div className="min-h-screen bg-gray-50">
<MeScreenHeader title="My Addresses" />
{isLoading ? (
<div className="flex min-h-[60vh] flex-1 items-center justify-center">
<p className="text-gray-600">Loading addresses...</p>
</div>
) : error ? (
<div className="flex min-h-[60vh] flex-1 flex-col items-center justify-center p-4">
<AlertTriangle className="h-12 w-12 text-red-500" />
<p className="mt-2 mb-4 text-center text-red-600">Failed to load addresses. Please try again.</p>
<button
onClick={() => refetch()}
className="rounded bg-blue-500 px-4 py-2 text-white"
>
Retry
</button>
</div>
) : (
<div className="mx-auto w-full max-w-2xl">
{/* Header row */}
<div className="flex flex-row items-center justify-between p-4 pb-2">
<p className="text-2xl font-bold text-gray-800">My Addresses</p>
<button
onClick={handleAddAddress}
aria-label="Add address"
className="rounded-full bg-blue-500 p-2 transition-colors hover:bg-blue-600"
>
<Plus className="h-6 w-6 text-white" />
</button>
</div>
{addresses.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12">
<MapPin className="h-16 w-16 text-gray-300" />
<p className="mb-2 mt-4 text-center text-gray-500">No addresses found</p>
<p className="mb-6 text-center text-gray-400">Add your first delivery address</p>
<button
onClick={handleAddAddress}
className="rounded-lg bg-blue-500 px-6 py-3 font-medium text-white transition-colors hover:bg-blue-600"
>
Add Address
</button>
</div>
) : (
<div className="p-4">
{addresses.map((address) => (
<AddressCard
key={address.id}
address={address}
onEdit={handleEditAddress}
onDelete={handleDeleteAddress}
onSetDefault={handleSetDefault}
isDeleting={deletingId === address.id}
/>
))}
</div>
)}
</div>
)}
{/* Add/Edit bottom sheet */}
<BottomDialog open={modalVisible} onClose={() => setModalVisible(false)}>
<div className="w-full">
<AddressForm
onSuccess={handleAddressSubmit}
initialValues={
editingAddress
? {
id: editingAddress.id,
regionId: editingAddress.regionId ?? undefined,
name: editingAddress.name,
phone: editingAddress.phone,
addressLine1: editingAddress.addressLine1,
addressLine2: editingAddress.addressLine2 || '',
city: editingAddress.city,
state: editingAddress.state,
isDefault: editingAddress.isDefault,
latitude: editingAddress.googleMapsUrl
? undefined
: editingAddress.latitude ?? undefined,
longitude: editingAddress.googleMapsUrl
? undefined
: editingAddress.longitude ?? undefined,
googleMapsUrl: editingAddress.googleMapsUrl ?? undefined,
}
: undefined
}
isEdit={!!editingAddress}
/>
</div>
</BottomDialog>
</div>
)
}