// frontend/src/components/Payments.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default function Payments({ token }) {
  const [tables, setTables] = useState([]);
  const [form, setForm] = useState({ TableNumber: '', AmountPaid: 0 });
  const [currentOrders, setCurrentOrders] = useState('');
  const [invoice, setInvoice] = useState(null);

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

  const fetchTables = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/tables');
      setTables(res.data);
    } catch (err) {
      console.error("Error fetching tables:", err);
    }
  };

  // Triggers automatically whenever a table is chosen from the dropdown
  const handleTableChange = (tableNum) => {
    if (!tableNum) {
      setForm({ TableNumber: '', AmountPaid: 0 });
      setCurrentOrders('');
      return;
    }

    const selectedTable = tables.find(t => t.TableNumber === parseInt(tableNum));
    
    // Look inside CustomerName for the embedded food selections
    if (selectedTable && selectedTable.CustomerName.includes('*Orders: [')) {
      const ordersString = selectedTable.CustomerName.split('*Orders: [')[1].replace(']*', '');
      setCurrentOrders(ordersString);

      // AUTOMATIC CALCULATION: Extracts digit figures from order notes
      const priceRegex = /(\d+)\s*Rwf/g;
      let totalSum = 0;
      let match;
      
      while ((match = priceRegex.exec(ordersString)) !== null) {
        totalSum += parseFloat(match[1]);
      }

      setForm({ TableNumber: tableNum, AmountPaid: totalSum });
    } else {
      setCurrentOrders('No pre-selected menu items found for this table.');
      setForm({ TableNumber: tableNum, AmountPaid: 0 });
    }
  };

  const handleProcessPayment = async (e) => {
    e.preventDefault();
    const targetTable = tables.find(t => t.TableNumber === parseInt(form.TableNumber));
    const today = new Date().toISOString().split('T')[0];

    // Clean customer name for display on the invoice receipt
    const cleanCustomerName = targetTable.CustomerName.split(' *Orders: [')[0];

    const payload = {
      TableNumber: form.TableNumber,
      AmountPaid: form.AmountPaid,
      PaymentDate: today
    };

    try {
      await axios.post('http://localhost:5000/api/payments', payload, { 
        headers: { Authorization: `Bearer ${token}` } 
      });
      
      // Construct receipt view data payload
      setInvoice({
        ...payload,
        CustomerName: cleanCustomerName,
        WaiterName: targetTable.WaiterName,
        Orders: currentOrders,
        InvoiceNo: Math.floor(100000 + Math.random() * 900000)
      });

      // Clear selection states safely
      setForm({ TableNumber: '', AmountPaid: 0 });
      setCurrentOrders('');
      
    } catch (err) {
      console.error("Error logging database transaction:", err);
    }
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
      
      {/* Automated Billing Entry Form */}
      <form onSubmit={handleProcessPayment} className="bg-white/5 border border-white/10 rounded-2xl p-6 space-y-5 h-fit">
        <h3 className="text-lg font-bold text-white">Process Table Settlement</h3>
        
        <div>
          <label className="block text-xs text-slate-400 mb-1">Select Active Table</label>
          <select 
            value={form.TableNumber} 
            onChange={e => handleTableChange(e.target.value)} 
            className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm focus:outline-none focus:border-amber-500" 
            required
          >
            <option value="">-- Choose Table --</option>
            {tables.map(t => {
              const cleanName = t.CustomerName.split(' *Orders: [')[0];
              return (
                <option key={t.TableNumber} value={t.TableNumber}>
                  Table {t.TableNumber} ({cleanName})
                </option>
              );
            })}
          </select>
        </div>

        {currentOrders && (
          <div className="p-3 bg-slate-900/80 border border-white/5 rounded-xl">
            <span className="block text-[10px] text-amber-400 font-bold uppercase tracking-wider mb-1">
              Detected Menu Choices:
            </span>
            <p className="text-xs text-slate-300 italic">{currentOrders}</p>
          </div>
        )}

        <div>
          <label className="block text-xs text-slate-400 mb-1">Calculated Amount Due</label>
          <input 
            type="text" 
            value={`${form.AmountPaid.toLocaleString()} Rwf`} 
            className="w-full bg-slate-950 border border-amber-500/30 rounded-lg p-3 text-amber-400 font-mono font-bold text-lg focus:outline-none cursor-not-allowed" 
            readOnly 
          />
        </div>

        <button 
          type="submit" 
          disabled={!form.TableNumber || form.AmountPaid === 0}
          className="w-full bg-emerald-500 text-slate-950 py-2.5 font-bold rounded-lg hover:bg-emerald-600 transition disabled:opacity-40 disabled:cursor-not-allowed"
        >
          Complete Transaction & Log Invoice
        </button>
      </form>

      {/* Modern Dynamic Print Receipt View */}
      <div>
        {invoice ? (
          <div className="bg-white text-slate-900 p-6 rounded-2xl shadow-2xl border-t-8 border-amber-500 font-mono text-xs animate-fadeIn">
            <div className="text-center border-b border-dashed border-slate-300 pb-3 mb-3">
              <h2 className="text-base font-bold uppercase">Taste of Rwanda</h2>
              <p className="text-[10px] text-slate-500">Musanze, Northern Province</p>
            </div>
            
            <div className="space-y-1 mb-3">
              <p><strong>INVOICE:</strong> #{invoice.InvoiceNo}</p>
              <p><strong>DATE:</strong> {invoice.PaymentDate}</p>
              <p><strong>TABLE:</strong> Room Table {invoice.TableNumber}</p>
              <p><strong>GUEST:</strong> {invoice.CustomerName}</p>
            </div>
            
            <div className="bg-slate-50 p-2 rounded border border-slate-100 my-2 text-[11px] text-slate-700">
              <strong className="block text-[9px] text-slate-400 uppercase tracking-tight mb-1">
                Items Served:
              </strong>
              {invoice.Orders}
            </div>
            
            <div className="border-b border-dashed border-slate-300 pb-2 mb-2 flex justify-between font-bold text-sm text-emerald-700">
              <span>TOTAL COLLECTED:</span>
              <span>{invoice.AmountPaid.toLocaleString()} Rwf</span>
            </div>
            
            <div className="text-center pt-1 text-[10px]">
              <p>Receiver/Handled by: <span className="underline font-bold">{invoice.WaiterName}</span></p>
              <p className="mt-3 text-slate-400 font-sans">Murakoze Cyane!</p>
            </div>
          </div>
        ) : (
          <div className="h-full min-h-[220px] border border-dashed border-white/10 rounded-2xl flex flex-col items-center justify-center text-slate-500 text-sm p-4 text-center">
            <p>Select an active dining table session to compute payment parameters automatically.</p>
          </div>
        )}
      </div>

    </div>
  );
}