import React, { useState } from 'react';
import axios from 'axios';

function BillingPage({ reservationsList, loadSystemData, API_URL }) {
  const [selectedResId, setSelectedResId] = useState('');
  const [invoiceData, setInvoiceData] = useState(null);

  const handleFetchInvoice = async (id) => {
    setSelectedResId(id);
    try {
      const res = await axios.get(`${API_URL}/invoice/${id}`);
      setInvoiceData(res.data);
    } catch (err) {
      alert('Invoice context maps could not be fetched.');
    }
  };

  const handleSettlePayment = async () => {
    if (!invoiceData) return;
    const total = invoiceData.items.reduce((sum, item) => sum + parseFloat(item.SubTotal), 0);
    try {
      await axios.post(`${API_URL}/payments`, {
        reservationId: selectedResId,
        amountPaid: total,
        paymentDate: new Date().toISOString().split('T')[0]
      });
      setInvoiceData(null);
      loadSystemData();
      alert('Payment processing finalized. Bill closed.');
    } catch (err) {
      alert('Payment execution sequence error.');
    }
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <div className="glass-panel p-6 rounded-2xl border border-slate-800 h-fit">
        <h2 className="text-xl font-bold mb-4">Active Accounts Registry</h2>
        <div className="space-y-2">
          {reservationsList.filter(r => r.Status === 'Active').map(r => (
            <button
              key={r.ReservationID}
              onClick={() => handleFetchInvoice(r.ReservationID)}
              className={`w-full text-left p-3 rounded-xl border text-sm transition-colors block ${
                selectedResId === r.ReservationID ? 'bg-amber-500/10 border-amber-500 text-amber-400' : 'bg-slate-900/50 border-slate-800 text-slate-300'
              }`}
            >
              Table {r.TableNumber} - Check out {r.CustomerName}
            </button>
          ))}
        </div>
      </div>

      <div className="lg:col-span-2 glass-panel p-6 rounded-2xl border border-slate-800">
        <h2 className="text-xl font-bold mb-4">Live Dynamic Statement Matrix View</h2>
        {invoiceData ? (
          <div className="space-y-6">
            <div className="border-b border-slate-800 pb-4 text-sm text-slate-400 space-y-1">
              <div>Invoice Handle: <span className="text-slate-200">#INV-00{invoiceData.meta.ReservationID}</span></div>
              <div>Assigned Customer: <span className="text-slate-200">{invoiceData.meta.CustomerName}</span></div>
              <div>Serving Server Account: <span className="text-slate-200">{invoiceData.meta.WaiterName}</span></div>
            </div>
            <div className="space-y-2">
              {invoiceData.items.map((item, i) => (
                <div key={i} className="flex justify-between text-sm py-1 border-b border-slate-900">
                  <span>{item.ItemName} <b className="text-slate-500">x{item.Quantity}</b></span>
                  <span className="font-mono text-slate-300">{parseFloat(item.SubTotal).toLocaleString()} RWF</span>
                </div>
              ))}
            </div>
            <div className="flex justify-between items-center pt-4 border-t border-slate-800">
              <span className="text-base font-bold">Total Bill Matrix Settlement Amount</span>
              <span className="text-2xl font-black text-emerald-400">
                {invoiceData.items.reduce((sum, item) => sum + parseFloat(item.SubTotal), 0).toLocaleString()} RWF
              </span>
            </div>
            <button onClick={handleSettlePayment} className="w-full bg-emerald-500 hover:bg-emerald-600 text-slate-950 font-black py-4 rounded-xl tracker">
              Finalize Billing Clearance
            </button>
          </div>
        ) : (
          <div className="text-center text-sm text-slate-500 py-12">Select an active check from the registry to print data view.</div>
        )}
      </div>
    </div>
  );
}

export default BillingPage;