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

function PaymentPage() {
  const [records, setRecords] = useState([]);
  const [payments, setPayments] = useState([]);
  const [bill, setBill] = useState(null);
  const [form, setForm] = useState({
    paymentNumber: "",
    amountPaid: "",
    paymentDate: "",
    receiverName: "",
    serviceRecord: "",
  });

  const loadAll = async () => {
    const [recordsRes, paymentsRes] = await Promise.all([api.get("/service-records"), api.get("/payments")]);
    setRecords(recordsRes.data);
    setPayments(paymentsRes.data);
  };

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

  const submit = async (e) => {
    e.preventDefault();
    await api.post("/payments", { ...form, amountPaid: Number(form.amountPaid) });
    setForm({ amountPaid: "", paymentDate: "", receiverName: "", serviceRecord: "" });
    await loadAll();
  };

  const generateBill = async (id) => {
    const { data } = await api.get(`/payments/bill/${id}`);
    setBill(data);
  };

  return (
    <section className="grid gap-6 lg:grid-cols-3">
      <form onSubmit={submit} className="rounded-xl bg-white p-5 shadow">
        <h2 className="mb-4 text-xl font-bold text-slate-800">Record Payment</h2>
        <input className="mb-2 w-full rounded border px-3 py-2" type="number" placeholder="Amount Paid" value={form.amountPaid} onChange={(e) => setForm({ ...form, amountPaid: e.target.value })} required />
        <input className="mb-2 w-full rounded border px-3 py-2" type="date" value={form.paymentDate} onChange={(e) => setForm({ ...form, paymentDate: e.target.value })} required />
        <input className="mb-2 w-full rounded border px-3 py-2" placeholder="Receiver (User)" value={form.receiverName} onChange={(e) => setForm({ ...form, receiverName: e.target.value })} required />
        <select className="mb-2 w-full rounded border px-3 py-2" value={form.serviceRecord} onChange={(e) => setForm({ ...form, serviceRecord: e.target.value })} required>
          <option value="">Select Service Record</option>
          {records.map((r) => <option key={r._id} value={r._id}>{r.recordNumber} - {r.car?.plateNumber}</option>)}
        </select>
        <button className="rounded bg-cyan-700 px-4 py-2 text-white">Save Payment</button>
      </form>
      <div className="rounded-xl bg-white p-5 shadow lg:col-span-2">
        <h2 className="mb-4 text-xl font-bold text-slate-800">Payments and Bill Generator</h2>
        <div className="space-y-2 text-sm">
          {payments.map((p) => (
            <div key={p._id} className="flex items-center justify-between rounded border p-2">
              <span>{p.paymentNumber} - {p.serviceRecord?.car?.plateNumber} - {p.amountPaid} RWF</span>
              <button className="rounded bg-indigo-700 px-3 py-1 text-white" onClick={() => generateBill(p._id)}>Generate Bill</button>
            </div>
          ))}
        </div>
        {bill ? (
          <div className="mt-4 rounded-lg border border-indigo-200 bg-indigo-50 p-4">
            <p className="font-bold">Bill #{bill.billNumber}</p>
            <p>Receiver: {bill.receiver}</p>
            <p>Car: {bill.plateNumber} ({bill.carModel})</p>
            <p>Service: {bill.serviceName}</p>
            <p>Paid: {bill.amountPaid} RWF</p>
          </div>
        ) : null}
      </div>
    </section>
  );
}

export default PaymentPage;
