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

export default function TableManagement({ token }) {
  const [tables, setTables] = useState([]);
  const [menuItems, setMenuItems] = useState([]);
  const [form, setForm] = useState({ 
    TableNumber: '', 
    CustomerName: '', 
    GuestCount: '', 
    Phone: '', 
    WaiterName: '' 
  });
  const [selectedItems, setSelectedItems] = useState([]);

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

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

  const fetchMenu = async () => {
    const res = await axios.get('http://localhost:5000/api/menu');
    setMenuItems(res.data);
  };

  const handleCheckboxChange = (itemName, itemPrice) => {
    const alreadySelected = selectedItems.find(i => i.name === itemName);
    if (alreadySelected) {
      setSelectedItems(selectedItems.filter(i => i.name !== itemName));
    } else {
      setSelectedItems([...selectedItems, { name: itemName, price: parseFloat(itemPrice) }]);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 1. Build a clean comma-separated text string of the selected menu orders
    const orderSummary = selectedItems.length > 0 
      ? selectedItems.map(i => `${i.name} (${i.price} Rwf)`).join(', ')
      : 'None';

    // 2. We attach the text right into the CustomerName string value 
    // so it bypasses your strict database column restrictions safely!
    const updatedForm = {
      ...form,
      CustomerName: `${form.CustomerName} *Orders: [${orderSummary}]*`
    };

    try {
      await axios.post('http://localhost:5000/api/tables', updatedForm, { 
        headers: { Authorization: `Bearer ${token}` } 
      });

      // Reset everything on success
      setForm({ TableNumber: '', CustomerName: '', GuestCount: '', Phone: '', WaiterName: '' });
      setSelectedItems([]);
      fetchTables();
    } catch (err) {
      console.error("Error saving table session:", err);
    }
  };

  return (
    <div className="space-y-8">
      {/* Table Session Registry Form */}
      <form onSubmit={handleSubmit} className="bg-white/5 border border-white/10 rounded-2xl p-6 space-y-6">
        <h3 className="text-lg font-bold text-white">Open New Table Session</h3>
        
        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <div>
            <label className="block text-xs text-slate-400 mb-1">Table #</label>
            <input type="number" placeholder="Table" 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 />
          </div>
          <div>
            <label className="block text-xs text-slate-400 mb-1">Customer Name</label>
            <input type="text" placeholder="Name" value={form.CustomerName} onChange={e => setForm({...form, CustomerName: e.target.value})} className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm" required />
          </div>
          <div>
            <label className="block text-xs text-slate-400 mb-1">Guests</label>
            <input type="number" placeholder="Count" value={form.GuestCount} onChange={e => setForm({...form, GuestCount: e.target.value})} className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm" required />
          </div>
          <div>
            <label className="block text-xs text-slate-400 mb-1">Phone Number</label>
            <input type="text" placeholder="Phone" value={form.Phone} onChange={e => setForm({...form, Phone: e.target.value})} className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm" required />
          </div>
          <div>
            <label className="block text-xs text-slate-400 mb-1">Waiter Name</label>
            <input type="text" placeholder="Waiter" value={form.WaiterName} onChange={e => setForm({...form, WaiterName: e.target.value})} className="w-full bg-slate-900 border border-white/10 rounded-lg p-2 text-white text-sm" required />
          </div>
        </div>

        {/* Dynamic Interactive Menu Checkboxes */}
        <div className="border-t border-white/10 pt-4">
          <label className="block text-xs font-semibold uppercase tracking-wider text-amber-400 mb-3">Select Ordered Items</label>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
            {menuItems.map(item => (
              <label key={item.MenuID} className="flex items-center space-x-3 bg-slate-900/50 p-3 rounded-xl border border-white/5 cursor-pointer hover:bg-slate-900 transition">
                <input 
                  type="checkbox" 
                  checked={selectedItems.some(i => i.name === item.ItemName)}
                  onChange={() => handleCheckboxChange(item.ItemName, item.ItemPrice)}
                  className="rounded text-amber-500 focus:ring-0 bg-slate-950 border-white/20 w-4 h-4"
                />
                <div className="text-xs">
                  <p className="text-white font-medium">{item.ItemName}</p>
                  <p className="text-slate-400 font-mono">{parseFloat(item.ItemPrice).toLocaleString()} Rwf</p>
                </div>
              </label>
            ))}
          </div>
        </div>

        <button type="submit" className="w-full bg-amber-500 text-slate-950 py-2.5 font-bold rounded-lg transition hover:bg-amber-600">
          Save Session with Menu Selection
        </button>
      </form>

      {/* Main Table View Panel */}
      <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">Table</th>
              <th className="p-4">Customer Info</th>
              <th className="p-4">Assigned Waiter</th>
              <th className="p-4">Items Ordered</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {tables.map(t => {
              // Standard safe guard clause logic against empty/null rows inside database tracking loop
              const nameString = t.CustomerName || "";
              
              // Extract order details string logic securely on client rendering pipeline
              const hasOrders = nameString.includes('*Orders: [');
              const displayCustomer = hasOrders ? nameString.split(' *Orders: [')[0] : nameString;
              const displayOrders = hasOrders ? nameString.split('*Orders: [')[1].replace(']*', '') : 'None selected';
              
              return (
                <tr key={t.TableNumber} className="hover:bg-white/5 transition">
                  <td className="p-4 font-bold text-amber-400">Table {t.TableNumber}</td>
                  <td className="p-4 text-white">
                    {displayCustomer} 
                    <span className="block text-xs text-slate-400 mt-0.5">Phone: {t.Phone}</span>
                  </td>
                  <td className="p-4"><span className="text-blue-400 font-medium">{t.WaiterName}</span></td>
                  <td className="p-4 text-xs text-amber-300/90 font-medium italic max-w-xs truncate">
                    {displayOrders}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}