import React, { useState, useEffect } from 'react';
import { 
  Plus, Utensils, Calendar, Users, LogOut, LayoutDashboard, 
  PlusCircle, AlertCircle, Settings, MapPin, Clock, Menu as MenuIcon, 
  Trash2, Upload, DollarSign, TextQuote 
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

const OwnerDashboard = () => {
  const [activeTab, setActiveTab] = useState('bookings');
  const [restaurant, setRestaurant] = useState(null);
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [newTable, setNewTable] = useState({ number: '', capacity: 2 });
  const [tables, setTables] = useState([]);
  const [menuItems, setMenuItems] = useState([]);
  const [newMenuItem, setNewMenuItem] = useState({ name: '', price: '', category: 'Main Course' });
  const [profileData, setProfileData] = useState({
      name: '',
      location: '',
      cuisine: '',
      priceRange: '$$$',
      description: '',
      openingTime: '',
      closingTime: ''
  });
  const [imageFile, setImageFile] = useState(null);
  
  const navigate = useNavigate();
  const userInfo = React.useMemo(() => JSON.parse(localStorage.getItem('userInfo')), []);

  useEffect(() => {
    if (!userInfo || userInfo.role !== 'owner') {
      navigate('/owner-login');
      return;
    }

    const fetchOwnerData = async () => {
      try {
        const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
        
        // Fetch bookings for owner's restaurants
        const { data: bookingsData } = await axios.get('http://localhost:5000/api/bookings/owner', config);
        setBookings(bookingsData);

        // Fetch owner's restaurant info
        const { data: restaurantData } = await axios.get('http://localhost:5000/api/restaurants', config);
        const myRestaurant = restaurantData.find(r => r.owner === userInfo._id || r.owner._id === userInfo._id);
        if (myRestaurant) {
            setRestaurant(myRestaurant);
            setTables(myRestaurant.tables || []);
            setMenuItems(myRestaurant.menu || []);
            setProfileData({
                name: myRestaurant.name || '',
                location: myRestaurant.location || '',
                cuisine: myRestaurant.cuisine || '',
                priceRange: myRestaurant.priceRange || '$$$',
                description: myRestaurant.description || '',
                openingTime: myRestaurant.openingTime || '',
                closingTime: myRestaurant.closingTime || ''
            });
        }
      } catch (err) {
        console.error(err);
        setError('Failed to fetch dashboard data');
      } finally {
        setLoading(false);
      }
    };

    fetchOwnerData();
  }, [userInfo, navigate]);

  const handleUpdateProfile = async (e) => {
      e.preventDefault();
      try {
          const formData = new FormData();
          Object.keys(profileData).forEach(key => formData.append(key, profileData[key]));
          formData.append('menu', JSON.stringify(menuItems));
          if (imageFile) formData.append('image', imageFile);

          const config = { 
              headers: { 
                  Authorization: `Bearer ${userInfo.token}`,
                  'Content-Type': 'multipart/form-data'
              } 
          };

          const { data } = await axios.put('http://localhost:5000/api/restaurants/profile', formData, config);
          setRestaurant(data);
          alert('Profile updated successfully!');
      } catch (err) {
          alert('Update failed');
      }
  };

  const handleAddMenuItem = () => {
      if (!newMenuItem.name || !newMenuItem.price) return;
      setMenuItems([...menuItems, { ...newMenuItem, id: Date.now() }]);
      setNewMenuItem({ name: '', price: '', category: 'Main Course' });
  };

  const removeMenuItem = (index) => {
      setMenuItems(menuItems.filter((_, i) => i !== index));
  };

  const handleAddTable = async () => {
    if (!newTable.number) { alert('Please enter a table number'); return; }
    try {
        const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
        const updatedTables = [...tables, { ...newTable }];
        await axios.put('http://localhost:5000/api/restaurants/tables', { tables: updatedTables }, config);
        setTables(updatedTables);
        setNewTable({ number: '', capacity: 2 });
    } catch (err) { alert('Failed to save table'); }
  };

  const handleRemoveTable = async (tableId) => {
    if (!window.confirm('Remove this table?')) return;
    try {
        const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
        const updatedTables = tables.filter(t => (t._id !== tableId && t.id !== tableId));
        await axios.put('http://localhost:5000/api/restaurants/tables', { tables: updatedTables }, config);
        setTables(updatedTables);
    } catch (err) { alert('Failed to remove table'); }
  };

  if (loading) return <div className="pt-32 text-center text-gray-500 font-bold h-screen bg-gray-50">Loading Dashboard...</div>;

  return (
    <div className="flex min-h-screen bg-[#f8f9fa] pt-20">
      {/* Sidebar */}
      <aside className="w-80 bg-white border-r border-gray-100 flex flex-col p-8 fixed h-full shadow-sm">
        <div className="mb-12">
            <div className="flex items-center gap-3 mb-6">
                <div className="w-12 h-12 bg-primary rounded-2xl flex items-center justify-center text-white shadow-lg">
                    <Utensils size={24} />
                </div>
                <h2 className="text-xl font-bold font-outfit text-secondary">Business Console</h2>
            </div>
            <div className="bg-gray-50 p-4 rounded-2xl">
                <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest mb-1">Owner</p>
                <p className="text-sm font-bold text-secondary">{userInfo?.name}</p>
            </div>
        </div>

        <nav className="flex-1 space-y-2">
          {[
            { id: 'bookings', label: 'Reservations', icon: Calendar },
            { id: 'profile', label: 'Restaurant Profile', icon: Settings },
            { id: 'tables', label: 'Manage Tables', icon: LayoutDashboard },
          ].map(tab => (
            <button 
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`w-full flex items-center gap-4 px-6 py-4 rounded-2xl font-bold transition-all ${activeTab === tab.id ? 'bg-secondary text-white shadow-xl' : 'text-gray-400 hover:bg-gray-50 hover:text-secondary'}`}
            >
              <tab.icon size={20} />
              {tab.label}
            </button>
          ))}
        </nav>

        <div className="pt-8 border-t border-gray-50">
            <button 
              onClick={() => { localStorage.removeItem('userInfo'); navigate('/login'); }}
              className="w-full flex items-center gap-4 px-6 py-4 text-red-500 font-bold hover:bg-red-50 rounded-2xl transition-all"
            >
              <LogOut size={20} />
              Sign Out
            </button>
        </div>
      </aside>

      {/* Main Content */}
      <main className="flex-1 ml-80 p-12">
        <header className="mb-12">
          <h1 className="text-4xl font-bold text-secondary font-outfit tracking-tight">
            {activeTab === 'bookings' ? 'Guest Arrivals' : activeTab === 'profile' ? 'Restaurant Information' : 'Table Inventory'}
          </h1>
          <p className="text-gray-400 font-medium text-lg">Manage your culinary business details and bookings.</p>
        </header>

        {error && <div className="bg-red-50 text-red-500 p-6 rounded-[32px] mb-8 font-bold border border-red-100">{error}</div>}

        {activeTab === 'bookings' && (
           <div className="bg-white rounded-[40px] shadow-sm border border-gray-100 overflow-hidden">
                <table className="w-full text-left">
                <thead className="bg-gray-50">
                    <tr className="border-b border-gray-100">
                    <th className="px-10 py-6 text-xs font-bold text-gray-400 uppercase tracking-widest">Customer</th>
                    <th className="px-10 py-6 text-xs font-bold text-gray-400 uppercase tracking-widest">Date & Time</th>
                    <th className="px-10 py-6 text-xs font-bold text-gray-400 uppercase tracking-widest">Party Size</th>
                    <th className="px-10 py-6 text-xs font-bold text-gray-400 uppercase tracking-widest">Status</th>
                    </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                    {bookings.length > 0 ? bookings.map((booking) => (
                    <tr key={booking._id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-10 py-8">
                            <div className="font-bold text-secondary">{booking.user?.name}</div>
                            <div className="text-xs text-gray-400">{booking.user?.email}</div>
                        </td>
                        <td className="px-10 py-8 font-bold text-secondary">
                            {booking.bookingDate} <br />
                            <span className="text-primary text-xs tracking-widest">{booking.bookingTime}</span>
                        </td>
                        <td className="px-10 py-8">
                            <div className="bg-gray-50 px-4 py-2 rounded-xl font-bold text-secondary w-fit border border-gray-100 flex items-center gap-2">
                                <Users size={14} /> {booking.guests} Guests
                            </div>
                        </td>
                        <td className="px-10 py-8">
                            <span className="px-4 py-1.5 rounded-full text-[10px] font-bold bg-green-100 text-green-600">CONFIRMED</span>
                        </td>
                    </tr>
                    )) : <tr><td colSpan="4" className="px-10 py-20 text-center text-gray-400 italic">No reservations yet.</td></tr>}
                </tbody>
                </table>
           </div>
        )}

        {activeTab === 'profile' && (
            <form onSubmit={handleUpdateProfile} className="space-y-10">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-10">
                    {/* General Info */}
                    <div className="bg-white p-10 rounded-[48px] shadow-sm border border-gray-100 space-y-6">
                        <h3 className="text-2xl font-bold text-secondary mb-6 flex items-center gap-3">
                            <TextQuote size={24} className="text-primary" /> Core Information
                        </h3>
                        <div className="space-y-4">
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Restaurant Title</label>
                                <input type="text" value={profileData.name} onChange={(e) => setProfileData({...profileData, name: e.target.value})} className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold" />
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-1">
                                    <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Category / Cuisine</label>
                                    <input type="text" value={profileData.cuisine} onChange={(e) => setProfileData({...profileData, cuisine: e.target.value})} className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold placeholder:font-normal" placeholder="e.g. Italian" />
                                </div>
                                <div className="space-y-1">
                                    <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Price Range</label>
                                    <select value={profileData.priceRange} onChange={(e) => setProfileData({...profileData, priceRange: e.target.value})} className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold">
                                        <option value="$">$ Budget</option>
                                        <option value="$$">$$ Medium</option>
                                        <option value="$$$">$$$ Premium</option>
                                        <option value="$$$$">$$$$ Elite</option>
                                    </select>
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Location / Address</label>
                                <div className="relative">
                                    <MapPin className="absolute left-6 top-4 text-primary" size={18} />
                                    <input type="text" value={profileData.location} onChange={(e) => setProfileData({...profileData, location: e.target.value})} className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-14 py-4 focus:border-primary outline-none font-bold" />
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Restaurant Image</label>
                                <div className="flex items-center gap-4">
                                    <input type="file" onChange={(e) => setImageFile(e.target.files[0])} className="hidden" id="image-upload" />
                                    <label htmlFor="image-upload" className="flex-1 bg-gray-50 border border-dashed border-gray-300 rounded-2xl p-6 flex flex-col items-center justify-center cursor-pointer hover:bg-gray-100 transition-all">
                                        <Upload size={24} className="text-primary mb-2" />
                                        <span className="text-xs font-bold text-gray-500 uppercase">{imageFile ? imageFile.name : 'Choose Banner Image'}</span>
                                    </label>
                                    {restaurant?.image && <img src={`http://localhost:5000/${restaurant.image}`} className="w-20 h-20 rounded-2xl object-cover shadow-lg" alt="current" />}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Business Hours & Desc */}
                    <div className="bg-white p-10 rounded-[48px] shadow-sm border border-gray-100 space-y-6">
                        <h3 className="text-2xl font-bold text-secondary mb-6 flex items-center gap-3">
                            <Clock size={24} className="text-primary" /> Business Hours & Description
                        </h3>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Opening Time</label>
                                <input type="text" value={profileData.openingTime} onChange={(e) => setProfileData({...profileData, openingTime: e.target.value})} placeholder="10:00 AM" className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold" />
                            </div>
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Closing Time</label>
                                <input type="text" value={profileData.closingTime} onChange={(e) => setProfileData({...profileData, closingTime: e.target.value})} placeholder="10:00 PM" className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold" />
                            </div>
                        </div>
                        <div className="space-y-1">
                            <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">About Restaurant</label>
                            <textarea value={profileData.description} onChange={(e) => setProfileData({...profileData, description: e.target.value})} rows="5" className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold leading-relaxed" placeholder="Tell us about your restaurant..."></textarea>
                        </div>
                    </div>
                </div>

                {/* Menu Management */}
                <div className="bg-white p-10 rounded-[48px] shadow-sm border border-gray-100">
                    <h3 className="text-2xl font-bold text-secondary mb-8 flex items-center gap-3">
                        <MenuIcon size={24} className="text-primary" /> Signature Menu items
                    </h3>
                    
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-6 items-end mb-10 bg-gray-50 p-6 rounded-[32px] border border-gray-100">
                        <div className="md:col-span-1 space-y-1">
                            <label className="text-[10px] font-bold text-gray-400 uppercase">Item Name</label>
                            <input type="text" value={newMenuItem.name} onChange={(e) => setNewMenuItem({...newMenuItem, name: e.target.value})} className="w-full bg-white border border-gray-100 rounded-xl px-4 py-3 outline-none" />
                        </div>
                        <div className="md:col-span-1 space-y-1">
                            <label className="text-[10px] font-bold text-gray-400 uppercase">Price ($)</label>
                            <input type="number" value={newMenuItem.price} onChange={(e) => setNewMenuItem({...newMenuItem, price: e.target.value})} className="w-full bg-white border border-gray-100 rounded-xl px-4 py-3 outline-none" />
                        </div>
                        <div className="md:col-span-1 space-y-1">
                            <label className="text-[10px] font-bold text-gray-400 uppercase">Category</label>
                            <select value={newMenuItem.category} onChange={(e) => setNewMenuItem({...newMenuItem, category: e.target.value})} className="w-full bg-white border border-gray-100 rounded-xl px-4 py-3 outline-none">
                                <option>Main Course</option>
                                <option>Starters</option>
                                <option>Desserts</option>
                                <option>Beverages</option>
                            </select>
                        </div>
                        <button type="button" onClick={handleAddMenuItem} className="bg-primary text-white font-bold py-3 px-8 rounded-xl shadow-lg hover:scale-105 active:scale-95 transition-all">Add Dish</button>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {menuItems.map((item, index) => (
                            <div key={index} className="flex justify-between items-center bg-gray-50 p-6 rounded-2xl border border-gray-100 group hover:border-primary transition-all">
                                <div className="flex gap-4">
                                    <div className="w-12 h-12 bg-white rounded-lg flex items-center justify-center font-bold text-primary shadow-sm">{item.name.charAt(0)}</div>
                                    <div>
                                        <p className="font-bold text-secondary">{item.name}</p>
                                        <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">{item.category}</p>
                                    </div>
                                </div>
                                <div className="flex items-center gap-6">
                                    <span className="font-bold text-primary text-lg">${item.price}</span>
                                    <button type="button" onClick={() => removeMenuItem(index)} className="text-gray-300 hover:text-red-500 transition-colors"><Trash2 size={18} /></button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                <div className="flex justify-end">
                    <button type="submit" className="bg-secondary text-white px-12 py-5 rounded-[24px] font-bold text-xl shadow-2xl hover:bg-black transition-all hover:scale-[1.02] active:scale-95">Save Business Profile</button>
                </div>
            </form>
        )}

        {activeTab === 'tables' && (
           <div className="space-y-12">
                <section className="bg-white p-10 rounded-[48px] shadow-sm border border-gray-100">
                    <h3 className="text-2xl font-bold text-secondary mb-8">Deploy New Table</h3>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-8 items-end">
                        <div className="space-y-1">
                            <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Table Number</label>
                            <input type="text" value={newTable.number} onChange={(e) => setNewTable({...newTable, number: e.target.value})} placeholder="e.g. T-01" className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold" />
                        </div>
                        <div className="space-y-1">
                            <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Guest Capacity</label>
                            <select value={newTable.capacity} onChange={(e) => setNewTable({...newTable, capacity: e.target.value})} className="w-full bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:border-primary outline-none font-bold">
                                {[2, 4, 6, 8, 10].map(n => <option key={n} value={n}>{n} Persons</option>)}
                            </select>
                        </div>
                        <button type="button" onClick={handleAddTable} className="bg-primary text-white py-4 rounded-2xl font-bold shadow-lg flex items-center justify-center gap-2 h-[60px]"><PlusCircle size={20} /> Add to System</button>
                    </div>
                </section>

                <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
                    {tables.map((table, i) => (
                        <div key={i} className="bg-white p-8 rounded-[40px] shadow-sm border border-gray-100 group relative overflow-hidden transition-all hover:shadow-xl">
                            <div className="relative z-10">
                                <div className="w-12 h-12 bg-secondary text-white rounded-2xl flex items-center justify-center mb-6 group-hover:bg-primary transition-colors"><Utensils size={20} /></div>
                                <h4 className="text-2xl font-bold text-secondary mb-1">Table {table.number}</h4>
                                <p className="text-gray-400 font-medium mb-8 flex items-center gap-2"><Users size={14} /> {table.capacity} Capacity</p>
                                <button onClick={() => handleRemoveTable(table._id || table.id)} className="w-full bg-red-50 text-red-500 py-3 rounded-2xl text-xs font-bold hover:bg-red-100 transition-all">Remove</button>
                            </div>
                        </div>
                    ))}
                </div>
           </div>
        )}
      </main>
    </div>
  );
};

export default OwnerDashboard;
