// filepath: frontend/src/pages/TripChecklist.tsx
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { getTripItems, toggleTripItem } from "../api";

export default function TripChecklist({ trips }: { trips: any[] }) {
  const { id } = useParams();
  const [items, setItems] = useState<any[]>([]);

  useEffect(() => {
    if (id) {
      getTripItems(id).then(setItems);
    }
  }, [id]);

  const trip = trips.find((t) => t.id === id);

  if (!trip) return <div>Trip not found</div>;

  return (
    <div>
      <h2 className="font-bold text-xl mb-2">{trip.name}</h2>
      <p className="mb-4">{trip.start_date} – {trip.end_date}</p>
      <ul>
        {items.map((item) => (
          <li key={item.id} className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={item.checked}
              onChange={async () => {
                await toggleTripItem(item.id);
                const updated = await getTripItems(id!);
                setItems(updated);
              }}
            />
            <span>{item.name_calculated}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}