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

function ServicePage() {
  const [services, setServices] = useState([]);
  const [form, setForm] = useState({ serviceName: "", servicePrice: "" });

  const loadServices = async () => {
    const { data } = await api.get("/services");
    setServices(data);
  };

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

  const submit = async (e) => {
    e.preventDefault();
    await api.post("/services", { ...form, servicePrice: Number(form.servicePrice) });
    setForm({ serviceCode: "", serviceName: "", servicePrice: "" });
    loadServices();
  };

  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">Create Service</h2>
        <input className="mb-2 w-full rounded border px-3 py-2" placeholder="Service Name" value={form.serviceName} onChange={(e) => setForm({ ...form, serviceName: e.target.value })} required />
        <input className="mb-2 w-full rounded border px-3 py-2" type="number" placeholder="Service Price" value={form.servicePrice} onChange={(e) => setForm({ ...form, servicePrice: e.target.value })} required />
        <button className="rounded bg-cyan-700 px-4 py-2 text-white">Save Service</button>
      </form>
      <div className="rounded-xl bg-white p-5 shadow">
        <h2 className="mb-4 text-xl font-bold text-slate-800">Services</h2>
        <div className="space-y-2 text-sm">
          {services.map((service) => (
            <div key={service._id} className="rounded border p-2">
              {service.serviceCode} - {service.serviceName}: {service.servicePrice} RWF
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

export default ServicePage;
