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

export default function Menu({ token }) {
  const [menu, setMenu] = useState([]);
  const [form, setForm] = useState({ ItemName: '', ItemPrice: '' });

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    await axios.post('http://localhost:5000/api/menu', form, { headers: { Authorization: `Bearer ${token}` } });
    setForm({ ItemName: '', ItemPrice: '' });
    fetchMenu();
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <form onSubmit={handleSubmit} className="bg-white/5 border border-white/10 rounded-2xl p-6 h-fit space-y-4">
        <h3 className="text-lg font-bold text-white mb-2">Add Menu Item</h3>
        <div>
          <label className="block text-xs text-slate-400 mb-1">Item Name</label>
          <input type="text" placeholder="e.g., Akabenz" value={form.ItemName} onChange={e => setForm({...form, ItemName: 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">Price (Rwf)</label>
          <input type="number" placeholder="Price" value={form.ItemPrice} onChange={e => setForm({...form, ItemPrice: 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="w-full bg-amber-500 text-slate-950 py-2 font-semibold rounded-lg hover:bg-amber-600 transition">Save Menu Item</button>
      </form>

      <div className="lg:col-span-2 bg-white/5 border border-white/10 rounded-2xl p-6">
        <h3 className="text-lg font-bold text-white mb-4">Active Menu Services</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {menu.map(m => (
            <div key={m.MenuID} className="bg-slate-900/60 border border-white/5 rounded-xl p-4 flex justify-between items-center">
              <div>
                <p className="text-white font-medium">{m.ItemName}</p>
                <p className="text-xs text-slate-400">ID: #{m.MenuID}</p>
              </div>
              <p className="text-amber-400 font-bold">{parseFloat(m.ItemPrice).toLocaleString()} Rwf</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}