"use client"; import { useMemo, useState, useTransition } from "react"; import { useRouter } from "next/navigation"; import { createAddress, deleteAddress, type AddressInput } from "@/lib/api/addresses"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import type { Address, AddressLabel, City, Neighborhood } from "@/types/api"; const LABEL_OPTIONS: { value: AddressLabel; label: string }[] = [ { value: "home", label: "خانه" }, { value: "work", label: "محل کار" }, { value: "other", label: "سایر" }, ]; const emptyForm = { label: "home" as AddressLabel, title: "", full_address: "", plaque: "", floor: "", unit: "", recipient_name: "", recipient_phone: "", city_uuid: "", neighborhood_uuid: "", is_default: false, }; export function AddressList({ addresses, cities, neighborhoods, }: { addresses: Address[]; cities: City[]; neighborhoods: Neighborhood[]; }) { const router = useRouter(); const [isAdding, setIsAdding] = useState(false); const [form, setForm] = useState(emptyForm); const [error, setError] = useState(null); const [isPending, startTransition] = useTransition(); const filteredNeighborhoods = useMemo( () => neighborhoods.filter((n) => n.city.uuid === form.city_uuid), [neighborhoods, form.city_uuid], ); function handleDelete(uuid: string) { startTransition(async () => { await deleteAddress(uuid); router.refresh(); }); } function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); startTransition(async () => { const input: AddressInput = { ...form, neighborhood_uuid: form.neighborhood_uuid || undefined, latitude: 0, longitude: 0, }; const result = await createAddress(input); if (result.ok) { setForm(emptyForm); setIsAdding(false); router.refresh(); } else { setError(result.message); } }); } return (
{addresses.map((address) => (
{LABEL_OPTIONS.find((o) => o.value === address.label)?.label} {address.is_default && "· پیش‌فرض"} {address.full_address} {address.recipient_name} — {address.recipient_phone}
))} {addresses.length === 0 && !isAdding &&

آدرسی ثبت نشده است.

}
{isAdding ? (
{LABEL_OPTIONS.map((opt) => ( ))}
setForm((f) => ({ ...f, full_address: e.target.value }))} required />
setForm((f) => ({ ...f, plaque: e.target.value }))} /> setForm((f) => ({ ...f, floor: e.target.value }))} /> setForm((f) => ({ ...f, unit: e.target.value }))} />
setForm((f) => ({ ...f, recipient_name: e.target.value }))} required /> setForm((f) => ({ ...f, recipient_phone: e.target.value }))} required /> {error &&

{error}

}
) : ( )}
); }