import { useEffect, useState } from "react";
import api from "../services/api";

function CarPage() {
  const [cars, setCars] = useState([]);
  const [form, setForm] = useState({
    plateNumber: "",
    type: "",
    model: "",
    manufacturingYear: "",
    driverPhone: "",
    mechanicName: "",
  });

  const loadCars = async () => {
    const { data } = await api.get("/cars");
    setCars(data);
  };

  useEffect(() => {
    loadCars();
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    await api.post("/cars", { ...form, manufacturingYear: Number(form.manufacturingYear) });
    setForm({ plateNumber: "", type: "", model: "", manufacturingYear: "", driverPhone: "", mechanicName: "" });
    loadCars();
  };

  return (
    <section className="grid gap-6 md:grid-cols-2">
      <form onSubmit={submit} className="rounded-xl bg-white p-5 shadow">
        <h2 className="mb-4 text-xl font-bold text-slate-800">Register Car</h2>
        {Object.keys(form).map((field) => (
          <input
            key={field}
            placeholder={field}
            value={form[field]}
            onChange={(e) => setForm({ ...form, [field]: e.target.value })}
            className="mb-2 w-full rounded border px-3 py-2"
            required
          />
        ))}
        <button className="rounded bg-cyan-700 px-4 py-2 text-white">Save Car</button>
      </form>
      <div className="rounded-xl bg-white p-5 shadow">
        <h2 className="mb-4 text-xl font-bold text-slate-800">Cars List</h2>
        <div className="space-y-2 text-sm">
          {cars.map((car) => (
            <div key={car._id} className="rounded border p-2">
              {car.plateNumber} - {car.model} ({car.type})
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

export default CarPage;
