'use client'
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useQueryClient } from '@tanstack/react-query';
import { useUser } from '@/hooks/useUser';
import { getRootUrl } from '@/lib/utility';
export default function ShippingAddressPage() {
const router = useRouter();
const { data: user, isLoading, error } = useUser();
const queryClient = useQueryClient();
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
address1: '',
address2: '',
city: '',
state: '',
zipcode: '',
country: '',
});
const [status, setStatus] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
// Populate the form with user data once it's loaded
useEffect(() => {
if (user && user.profile) { // Add a check for user.profile
setFormData({
firstName: user.profile.firstName ?? user.name ?? '',
lastName: user.profile.lastName || '',
address1: user.profile.address1 || '',
address2: user.profile.address2 || '',
city: user.profile.city || '',
state: user.profile.state || '',
zipcode: user.profile.zipcode || '',
country: user.profile.country || '',
});
}
}, [user]);
// Handle form input changes
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setFormData(prevData => ({
...prevData,
[name]: value,
}));
};
// Handle form submission
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
setStatus('');
if (!user || !user.profile) { // Add a check for user.profile
setStatus('You must be logged in to update your address.');
setIsSubmitting(false);
return;
}
try {
const rootUrl = getRootUrl();
const profileId = user.profile.id; // Get the profileId here, after the user check
const res = await fetch(`${rootUrl}/api/profiles/${profileId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify(formData),
});
if (res.ok) {
await queryClient.invalidateQueries({ queryKey: ['user'] });
setStatus('Profile updated successfully!');
} else {
const errorData = await res.json();
setStatus(errorData.message || 'Failed to update profile.');
}
} catch (err) {
console.error('Update address error:', err);
setStatus('An unexpected error occurred. Please try again.');
} finally {
setIsSubmitting(false);
}
};
if (isLoading) {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24 bg-gray-100">
<p>Loading user data...</p>
</main>
);
}
if (error) {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24 bg-gray-100">
<p className="text-red-500">Error: Failed to load user data.</p>
</main>
);
}
if (!user) {
router.push('/login');
return null;
}
return (
<main className="flex flex-col">
<div className="bg-gray-600 p-8 rounded-lg shadow-md w-full max-w-md">
<h1 className="text-3xl font-bold mb-6 text-center">Update profile</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Input fields for all address components */}
<input
type="text"
name="firstName"
placeholder="First Name"
value={formData.firstName}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="lastName"
placeholder="Last Name"
value={formData.lastName}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="address1"
placeholder="Address Line 1"
value={formData.address1}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="address2"
placeholder="Address Line 2"
value={formData.address2}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="city"
placeholder="City"
value={formData.city}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="state"
placeholder="State/Province/Region"
value={formData.state}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="zipcode"
placeholder="Zip/Postal Code"
value={formData.zipcode}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
<input
type="text"
name="country"
placeholder="Country"
value={formData.country}
onChange={handleChange}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
{status && (
<p className={`text-sm text-center ${status.includes('success') ? 'text-green-500' : 'text-red-500'}`}>
{status}
</p>
)}
<button
type="submit"
disabled={isSubmitting}
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50"
>
{isSubmitting ? "Loading..." : 'Update Address'}
</button>
</form>
</div>
</main>
);
}