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

export default function Reservations({ token }) {
  const [reservations, setReservations] = useState([]);
  const [tables, setTables] = useState([]);
  const [form, setForm] = useState({ TableNumber: '', VisitDate: '' });
  const [editingId, setEditingId] = useState(null);

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

  const fetchReservations = async () => {
    const res = await axios.get('http://localhost:5000/api/reservations');
    setReservations(res.data);
  };

  const fetchTables = async () => {
    const res = await axios.get('http://localhost:5000/api/tables');
    setTables(res.data);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const config = { headers: { Authorization: `Bearer ${token}` } };
    if (editingId) {
      await axios.put(`http://localhost:5000/api/reservations/${editingId}`, form, config);
      setEditingId(null);
    } else {
      await axios.post('http://localhost:5000/api/reservations', form, config);
    }
    setForm({ TableNumber: '', VisitDate: '' });
    fetchReservations();
  };

  const handleEdit = (res) => {
    setEditingId(res.ReservationID);
    setForm({ TableNumber: res.TableNumber, VisitDate: res.VisitDate.split('T')[0] });
  };

  const handleDelete = async (id) => {
    if(confirm("Cancel this reservation?")) {
      await axios.delete(`http://localhost:5000/api/reservations/${id}`, { headers: { Authorization: `Bearer ${token}` } });
      fetchReservations();
    }
  };

  return (
    <div className="space-y-8">
      <form onSubmit={handleSubmit} className="bg-white/5 border border-white/10 rounded-2xl p-6 flex flex-wrap gap-4 items-end">
        <div className="flex-1 min-w-[200px]">
          <label className="block text-xs text-slate-400 mb-1">Select Active Table</label>
          <select value={form.TableNumber} onChange={e => setForm({...form, TableNumber: e.target.value})} className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm" required>
            <option value="">-- Choose Table --</option>
            {tables.map(t => <option key={t.TableNumber} value={t.TableNumber}>Table {t.TableNumber} ({t.CustomerName})</option>)}
          </select>
        </div>
        <div className="flex-1 min-w-[200px]">
          <label className="block text-xs text-slate-400 mb-1">Visit Date</label>
          <input type="date" value={form.VisitDate} onChange={e => setForm({...form, VisitDate: e.target.value})} className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm" required />
        </div>
        <button type="submit" className="bg-amber-500 text-slate-950 px-6 py-2 font-semibold rounded-lg hover:bg-amber-600 transition">
          {editingId ? 'Update Reservation' : 'Schedule Reservation'}
        </button>
      </form>

      <div className="bg-white/5 border border-white/10 rounded-2xl overflow-hidden">
        <table className="w-full text-left text-sm text-slate-300">
          <thead className="bg-white/5 text-white">
            <tr>
              <th className="p-4">ID</th>
              <th className="p-4">Table</th>
              <th className="p-4">Customer</th>
              <th className="p-4">Date</th>
              <th className="p-4 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {reservations.map(r => (
              <tr key={r.ReservationID} className="hover:bg-white/5">
                <td className="p-4">#{r.ReservationID}</td>
                <td className="p-4 font-semibold text-white">Table {r.TableNumber}</td>
                <td className="p-4">{r.CustomerName}</td>
                <td className="p-4">{new Date(r.VisitDate).toLocaleDateString()}</td>
                <td className="p-4 text-right space-x-2">
                  <button onClick={() => handleEdit(r)} className="text-amber-400 hover:underline text-xs bg-amber-500/10 px-2 py-1 rounded">Edit</button>
                  <button onClick={() => handleDelete(r.ReservationID)} className="text-rose-400 hover:underline text-xs bg-rose-500/10 px-2 py-1 rounded">Delete</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}