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

function ServiceRecordPage() {
  const [records, setRecords] = useState([]);
  const [cars, setCars] = useState([]);
  const [services, setServices] = useState([]);
  const [form, setForm] = useState({ serviceDate: "", car: "", service: "" });
  const [editingId, setEditingId] = useState("");

  const loadAll = async () => {
    const [recordsRes, carsRes, servicesRes] = await Promise.all([
      api.get("/service-records"),
      api.get("/cars"),
      api.get("/services"),
    ]);
    setRecords(recordsRes.data);
    setCars(carsRes.data);
    setServices(servicesRes.data);
  };

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

  const submit = async (e) => {
    e.preventDefault();
    if (editingId) await api.put(`/service-records/${editingId}`, form);
    else await api.post("/service-records", form);
    setForm({ recordNumber: "", serviceDate: "", car: "", service: "" });
    setEditingId("");
    loadAll();
  };

  const edit = (record) => {
    setEditingId(record._id);
    setForm({
      recordNumber: record.recordNumber,
      serviceDate: record.serviceDate.slice(0, 10),
      car: record.car?._id,
      service: record.service?._id,
    });
  };

  const remove = async (id) => {
    await api.delete(`/service-records/${id}`);
    loadAll();
  };

  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">Service Record </h2>
        <input className="mb-2 w-full rounded border px-3 py-2" type="date" value={form.serviceDate} onChange={(e) => setForm({ ...form, serviceDate: e.target.value })} required />
        <select className="mb-2 w-full rounded border px-3 py-2" value={form.car} onChange={(e) => setForm({ ...form, car: e.target.value })} required>
          <option value="">Select Car</option>
          {cars.map((car) => <option key={car._id} value={car._id}>{car.plateNumber}</option>)}
        </select>
        <select className="mb-2 w-full rounded border px-3 py-2" value={form.service} onChange={(e) => setForm({ ...form, service: e.target.value })} required>
          <option value="">Select Service</option>
          {services.map((service) => <option key={service._id} value={service._id}>{service.serviceName}</option>)}
        </select>
        <button className="rounded bg-cyan-700 px-4 py-2 text-white">{editingId ? "Update" : "Save"} Record</button>
      </form>
      <div className="rounded-xl bg-white p-5 shadow">
        <h2 className="mb-4 text-xl font-bold text-slate-800">Records</h2>
        <div className="space-y-2 text-sm">
          {records.map((record) => (
            <div key={record._id} className="rounded border p-2">
              <p>{record.recordNumber} | {record.car?.plateNumber} | {record.service?.serviceName}</p>
              <div className="mt-1 flex gap-2">
                <button className="rounded bg-amber-500 px-2 py-1 text-xs text-white" onClick={() => edit(record)}>Edit</button>
                <button className="rounded bg-red-600 px-2 py-1 text-xs text-white" onClick={() => remove(record._id)}>Delete</button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

export default ServiceRecordPage;
