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

function ReservationPage({ tablesList, reservationsList, loadSystemData, API_URL }) {
  const [resTable, setResTable] = useState('');
  const [resDate, setResDate] = useState('');

  const handleReservationSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`${API_URL}/reservations`, {
        tableNumber: resTable,
        visitDate: resDate
      });
      setResTable(''); setResDate('');
      loadSystemData();
    } catch (err) {
      alert('Error building booking confirmation record.');
    }
  };

  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">Book Table Entry Matrix</h2>
        <form onSubmit={handleReservationSubmit} className="space-y-4">
          <div>
            <label className="block text-xs font-semibold text-slate-400 mb-2">Select Target Active Table</label>
            <select value={resTable} onChange={(e) => setResTable(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5" required>
              <option value="">Choose Seat</option>
              {tablesList.map(t => <option key={t.TableNumber} value={t.TableNumber}>Table {t.TableNumber} ({t.CustomerName})</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-400 mb-2">Target Date Calendar</label>
            <input type="date" value={resDate} onChange={(e) => setResDate(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5" required />
          </div>
          <button type="submit" className="w-full bg-slate-100 hover:bg-white text-slate-950 font-bold py-3 rounded-xl transition-colors">Record Reservation</button>
        </form>
      </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">Active System Reservation Records Ledger</h2>
        <div className="space-y-3">
          {reservationsList.map(r => (
            <div key={r.ReservationID} className="p-4 bg-slate-900/60 border border-slate-800 rounded-xl flex justify-between items-center">
              <div>
                <div className="font-bold">Table {r.TableNumber} — {r.CustomerName}</div>
                <div className="text-xs text-slate-400 mt-1">Calendar: {new Date(r.VisitDate).toLocaleDateString()} | Status: <span className={r.Status === 'Paid' ? 'text-emerald-400' : 'text-amber-400'}>{r.Status}</span></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default ReservationPage;