// Edit Trip page.
//
// The Angular EditTripComponent located its record through a trip code
// stashed in localStorage by TripCardComponent — hidden shared state
// between two components, and an alert() if it was missing. This
// version reads the code from the URL (/edit-trip/:tripCode) with
// useParams, so the page is self-contained, bookmarkable, and
// refresh-safe.
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import TripForm from '../components/TripForm';
import { getTrip, updateTrip } from '../api/trip-api';
import { TripFormData } from '../models/trip';

export default function EditTrip() {
  const { tripCode } = useParams<{ tripCode: string }>();
  const navigate = useNavigate();
  const [initialValues, setInitialValues] = useState<TripFormData | null>(null);
  const [message, setMessage] = useState('Loading trip...');

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

    async function loadTrip() {
      if (!tripCode) {
        navigate('/');
        return;
      }
      try {
        const trip = await getTrip(tripCode);
        if (!isMounted) {
          return;
        }
        if (!trip) {
          setMessage('No Trip Retrieved!');
          return;
        }
        // Convert the ISO date string to yyyy-MM-dd for <input type="date">.
        setInitialValues({
          ...trip,
          start: trip.start ? trip.start.split('T')[0] : ''
        });
      } catch {
        if (isMounted) {
          setMessage('Unable to load this trip.');
        }
      }
    }

    loadTrip();
    return () => {
      isMounted = false;
    };
  }, [tripCode, navigate]);

  const handleSubmit = async (formData: TripFormData) => {
    await updateTrip(formData);
    navigate('/');
  };

  if (!initialValues) {
    return <p>{message}</p>;
  }

  return (
    <TripForm
      title="Edit Trip"
      initialValues={initialValues}
      onSubmit={handleSubmit}
    />
  );
}
