import React, { useState, useEffect } from 'react';
import axios from '../axiosInstance'

export default function Payments() {
  const [payments, setPayments] = useState([]);
  const [records, setRecords] = useState([]);
  const [form, setForm] = useState({ paymentNumber: '', amountPaid: '', paymentDate: '', serviceRecord: '' });

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

  const fetchPayments = async () => {
    try {
      const [pRes, rRes] = await Promise.all([
        axios.get('http://localhost:5000/api/payment'),
        axios.get('http://localhost:5000/api/servicerecord')
      ]);
      setPayments(pRes.data);
      setRecords(rRes.data);
    } catch (err) {
      console.error("Failed to load invoice items:", err);
    }
  };

  // Auto-fill price from seeds based on selected service record item
  const handleRecordChange = (recordId) => {
    const selectedRecord = records.find(r => r._id === recordId);
    const estimatedCost = selectedRecord?.service?.servicePrice || '';
    setForm({ ...form, serviceRecord: recordId, amountPaid: estimatedCost });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post('http://localhost:5000/api/payment', form);
      setForm({ paymentNumber: '', amountPaid: '', paymentDate: '', serviceRecord: '' });
      fetchPayments();
    } catch (err) {
      alert("Error logging payment invoice");
    }
  };

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      <h2 className="text-2xl font-black text-slate-800">Process Invoices & Receipts</h2>
      
      {/* Payment Processing Form */}
      <form onSubmit={handleSubmit} className="bg-white p-6 rounded-2xl border border-slate-200 grid grid-cols-1 md:grid-cols-4 gap-4 shadow-sm">
        <input 
          className="border p-3 rounded-xl text-sm w-full font-bold text-black" 
          placeholder="Receipt Ref (e.g. TXN-998)" 
          value={form.paymentNumber} 
          onChange={e => setForm({...form, paymentNumber: e.target.value})} 
          required 
        />
        <input 
          className="border p-3 rounded-xl text-sm w-full font-bold text-black" 
          type="date" 
          value={form.paymentDate} 
          onChange={e => setForm({...form, paymentDate: e.target.value})} 
          required 
        />
        <select 
          className="border p-3 rounded-xl text-sm bg-white w-full font-bold text-black"
          value={form.serviceRecord} 
          onChange={e => handleRecordChange(e.target.value)} 
          required
        >
          <option value="">-- Choose Job Record --</option>
          {records.map(r => (
            <option key={r._id} value={r._id}>
              {r.recordNumber} - {r.car?.number} ({r.service?.serviceName})
            </option>
          ))}
        </select>
        <input 
          className="border p-3 rounded-xl text-sm w-full font-bold bg-slate-50 text-emerald-700" 
          type="number"
          placeholder="Amount (RWF)" 
          value={form.amountPaid} 
          onChange={e => setForm({...form, amountPaid: e.target.value})}
          required 
        />
        <button type="submit" className="col-span-full bg-emerald-600 text-white font-semibold py-3 rounded-xl hover:bg-emerald-700 transition ">
          Process Settlement Receipt
        </button>
      </form>

      {/* Transactions Ledger */}
      <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
        <table className="w-full text-left text-sm text-slate-600">
          <thead className="bg-slate-50 text-xs uppercase font-bold text-slate-500 border-b border-slate-200">
            <tr>
              <th className="p-4">Receipt Ref</th>
              <th className="p-4">Clearing Date</th>
              <th className="p-4">Job Reference</th>
              <th className="p-4 text-right">Settled Balance</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {payments.map(p => (
              <tr key={p._id} className="hover:bg-slate-50">
                <td className="p-4 font-mono font-bold text-slate-900">{p.paymentNumber}</td>
                <td className="p-4">{p.paymentDate ? new Date(p.paymentDate).toLocaleDateString() : 'N/A'}</td>
                <td className="p-4 font-semibold text-slate-700">{p.serviceRecord?.recordNumber || 'Settled'}</td>
                <td className="p-4 text-right font-bold text-emerald-600">{(p.amountPaid || 0).toLocaleString()} RWF</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
