// Trip listing page. Port of the Angular TripListingComponent.
//
// Angular mapping (per the Module One plan and code review):
//   - ngOnInit + getStuff() subscription  ->  useEffect + async/await
//   - WritableSignal<Trip[]>              ->  useState<Trip[]>
//   - injected AuthenticationService      ->  useAuth() hook
//
// The effect also tracks loading and error state explicitly, which the
// original component logged to the console but never surfaced to the
// user.
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import TripCard from '../components/TripCard';
import { Trip } from '../models/trip';
import { getTrips } from '../api/trip-api';
import { useAuth } from '../context/AuthContext';

export default function TripListing() {
  const [trips, setTrips] = useState<Trip[]>([]);
  const [message, setMessage] = useState('Loading trips...');
  const { isLoggedIn } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    let isMounted = true;

    async function loadTrips() {
      try {
        const data = await getTrips();
        if (!isMounted) {
          return;
        }
        setTrips(data);
        setMessage(
          data.length > 0
            ? `There are ${data.length} trips available.`
            : 'There were no trips retrieved from the database'
        );
      } catch {
        if (isMounted) {
          setMessage('Unable to load trips. Is the API running?');
        }
      }
    }

    loadTrips();
    // Cleanup guard prevents state updates if the component unmounts
    // before the request resolves (the React equivalent of Angular
    // tearing down a subscription).
    return () => {
      isMounted = false;
    };
  }, []);

  return (
    <>
      {isLoggedIn && (
        <div className="row">
          <div className="col-12 mb-3">
            <button
              type="button"
              className="btn btn-primary"
              onClick={() => navigate('/add-trip')}
            >
              Add Trip
            </button>
          </div>
        </div>
      )}
      {trips.length === 0 && <p>{message}</p>}
      <div className="row">
        {trips.map((trip) => (
          <div className="col-md-4 col-sm-6 col-12 mb-3" key={trip.code}>
            <TripCard trip={trip} />
          </div>
        ))}
      </div>
    </>
  );
}
