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

function OrderPage({ API_URL }) {
  const [reservations, setReservations] = useState([]);
  const [menuItems, setMenuItems] = useState([]);
  const [selectedResId, setSelectedResId] = useState('');
  const [selectedMenuId, setSelectedMenuId] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [message, setMessage] = useState('');

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

  const fetchData = async () => {
    try {
      const resTickets = await axios.get(`${API_URL}/reservations`);
      setReservations(resTickets.data.filter(r => r.Status === 'Active'));
      
      const menuRes = await axios.get(`${API_URL}/menu`);
      setMenuItems(menuRes.data);
    } catch (err) {
      console.error('Failed to look up foundational operational context data matrices.', err);
    }
  };

  const handleAddOrder = async (e) => {
    e.preventDefault();
    if (!selectedResId || !selectedMenuId) {
      setMessage('Please pick an active reservation ticket and a menu item.');
      return;
    }

    try {
      await axios.post(`${API_URL}/orders`, {
        reservationId: selectedResId,
        menuId: selectedMenuId,
        quantity: parseInt(quantity)
      });
      setMessage('Item appended to order ticket successfully!');
      setQuantity(1);
      fetchData(); 
    } catch (err) {
      setMessage('Error processing item addition entry point.');
    }
  };

  return (
    <div className="space-y-6">
      <div className="glass-panel p-6 rounded-2xl border border-slate-800">
        <h2 className="text-2xl font-bold text-white mb-2">Service Point of Sale (POS) Orders</h2>
        <p className="text-sm text-slate-400 mb-6">Add kitchen menu items directly to an active table selection setup.</p>

        {message && (
          <div className="mb-4 p-3 bg-amber-500/10 border border-amber-500/20 text-amber-400 rounded-xl text-sm text-center">
            {message}
          </div>
        )}

        <form onSubmit={handleAddOrder} className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
          <div>
            <label className="block text-xs font-semibold text-slate-400 uppercase mb-2">Active Table Ticket</label>
            <select value={selectedResId} onChange={(e) => setSelectedResId(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-slate-200 focus:outline-none focus:border-amber-500" required>
              <option value="">Select Table Booking</option>
              {reservations.map(res => (
                <option key={res.ReservationID} value={res.ReservationID}>
                  Table {res.TableNumber} - {res.CustomerName}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-400 uppercase mb-2">Menu Item</label>
            <select value={selectedMenuId} onChange={(e) => setSelectedMenuId(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-slate-200 focus:outline-none focus:border-amber-500" required>
              <option value="">Select Item</option>
              {menuItems.map(item => (
                <option key={item.MenuID} value={item.MenuID}>
                  {item.ItemName} ({parseFloat(item.ItemPrice).toLocaleString()} RWF)
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-400 uppercase mb-2">Quantity</label>
            <input type="number" min="1" value={quantity} onChange={(e) => setQuantity(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-slate-200 focus:outline-none focus:border-amber-500" required />
          </div>

          <button type="submit" className="w-full bg-gradient-to-r from-amber-500 to-orange-600 text-white font-semibold py-3 rounded-xl shadow-lg">
            Add To Order
          </button>
        </form>
      </div>

      <div className="glass-panel p-6 rounded-2xl border border-slate-800">
        <h3 className="text-xl font-bold text-white mb-4">Current Active Live Orders Summary</h3>
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm text-slate-300">
            <thead className="text-xs uppercase bg-slate-950/60 text-slate-400 border-b border-slate-800">
              <tr>
                <th className="p-4">Table</th>
                <th className="p-4">Customer</th>
                <th className="p-4">Items Drafted</th>
                <th className="p-4">Accumulated Bill</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-800">
              {reservations.map(res => (
                <tr key={res.ReservationID} className="hover:bg-slate-900/40">
                  <td className="p-4 font-semibold text-amber-400">Table {res.TableNumber}</td>
                  <td className="p-4">{res.CustomerName}</td>
                  <td className="p-4 text-slate-400 italic">{res.OrderedItems || 'No items selected yet'}</td>
                  <td className="p-4 font-bold text-emerald-400">{parseFloat(res.TotalEstimate).toLocaleString()} RWF</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default OrderPage;