import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import { useAuth } from '../contexts/AuthContext'; import api from '../services/api'; import { Item, Rental } from '../types'; import { rentalAPI } from '../services/api'; const MyListings: React.FC = () => { const { user } = useAuth(); const [listings, setListings] = useState([]); const [rentals, setRentals] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); useEffect(() => { fetchMyListings(); fetchRentalRequests(); }, [user]); const fetchMyListings = async () => { if (!user) return; try { setLoading(true); setError(''); // Clear any previous errors const response = await api.get('/items'); // Filter items to only show ones owned by current user const myItems = response.data.items.filter((item: Item) => item.ownerId === user.id); setListings(myItems); } catch (err: any) { console.error('Error fetching listings:', err); // Only show error for actual API failures if (err.response && err.response.status >= 500) { setError('Failed to get your listings. Please try again later.'); } } finally { setLoading(false); } }; const handleDelete = async (itemId: string) => { if (!window.confirm('Are you sure you want to delete this listing?')) return; try { await api.delete(`/items/${itemId}`); setListings(listings.filter(item => item.id !== itemId)); } catch (err: any) { alert('Failed to delete listing'); } }; const toggleAvailability = async (item: Item) => { try { await api.put(`/items/${item.id}`, { ...item, availability: !item.availability }); setListings(listings.map(i => i.id === item.id ? { ...i, availability: !i.availability } : i )); } catch (err: any) { alert('Failed to update availability'); } }; const fetchRentalRequests = async () => { if (!user) return; try { const response = await rentalAPI.getMyListings(); setRentals(response.data); } catch (err) { console.error('Error fetching rental requests:', err); } }; const handleAcceptRental = async (rentalId: string) => { try { await rentalAPI.updateRentalStatus(rentalId, 'confirmed'); // Refresh the rentals list fetchRentalRequests(); } catch (err) { console.error('Failed to accept rental request:', err); } }; const handleRejectRental = async (rentalId: string) => { try { await api.put(`/rentals/${rentalId}/status`, { status: 'cancelled', rejectionReason: 'Request declined by owner' }); // Refresh the rentals list fetchRentalRequests(); } catch (err) { console.error('Failed to reject rental request:', err); } }; if (loading) { return (
Loading...
); } return (

My Listings

Add New Item
{error && (
{error}
)} {(() => { const pendingCount = rentals.filter(r => r.status === 'pending').length; if (pendingCount > 0) { return (
You have {pendingCount} pending rental request{pendingCount > 1 ? 's' : ''} to review.
); } return null; })()} {listings.length === 0 ? (

You haven't listed any items yet.

List Your First Item
) : (
{listings.map((item) => (
) => { const target = e.target as HTMLElement; if (target.closest('button') || target.closest('.rental-requests')) { e.preventDefault(); } }} >
{item.images && item.images[0] && ( {item.name} )}
{item.name}

{item.description}

{item.availability ? 'Available' : 'Not Available'}
{item.pricePerDay && (
${item.pricePerDay}/day
)} {item.pricePerHour && (
${item.pricePerHour}/hour
)}
{(() => { const pendingRentals = rentals.filter(r => r.itemId === item.id && r.status === 'pending' ); const acceptedRentals = rentals.filter(r => r.itemId === item.id && ['confirmed', 'active'].includes(r.status) ); if (pendingRentals.length > 0 || acceptedRentals.length > 0) { return (
{pendingRentals.length > 0 && ( <>
Pending Requests ({pendingRentals.length})
{pendingRentals.map(rental => (
{rental.renter?.firstName} {rental.renter?.lastName}
{new Date(rental.startDate).toLocaleDateString()} - {new Date(rental.endDate).toLocaleDateString()}
${rental.totalAmount}
))} )} {acceptedRentals.length > 0 && ( <>
Accepted Rentals ({acceptedRentals.length})
{acceptedRentals.map(rental => (
{rental.renter?.firstName} {rental.renter?.lastName}
{new Date(rental.startDate).toLocaleDateString()} - {new Date(rental.endDate).toLocaleDateString()}
${rental.totalAmount}
{rental.status === 'active' ? 'Active' : 'Confirmed'}
))} )}
); } return null; })()}
))}
)}
); }; export default MyListings;