import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Login from './components/Login';
import TablePage from './components/TablePage';
import ReservationPage from './components/ReservationPage';
import OrderPage from './components/OrderPage';
import BillingPage from './components/BillingPage';
import ReportPage from './components/ReportPage';

const API_URL = 'http://localhost:5000/api';
axios.defaults.withCredentials = true;

// --- INLINE INTERACTIVE DASHBOARD COMPONENT ---
function DashboardOverview({ tablesList, reservationsList, setActiveTab }) {
  // Compute metrics dynamically from application state lists
  const totalTables = tablesList.length;
  const activeReservations = reservationsList.filter(r => r.Status === 'Active').length;
  const totalPaidBookings = reservationsList.filter(r => r.Status === 'Paid').length;
  
  // Dynamic Calculation: Revenue aggregations
  const estimatedRevenue = reservationsList.reduce((acc, curr) => acc + (Number(curr.TotalEstimate) || 0), 0);

  return (
    <div className="space-y-8 animate-fadeIn">
      {/* Metrics Banner */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-5">
        <div className="bg-zinc-900 border border-zinc-800/80 p-5 rounded-2xl shadow-xl flex flex-col justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Floor Layout Status</p>
            <h3 className="text-3xl font-bold mt-2 text-white">{totalTables} Registered</h3>
          </div>
          <button onClick={() => setActiveTab('tables')} className="mt-4 text-xs font-medium text-emerald-500 hover:text-emerald-400 text-left flex items-center space-x-1">
            <span>Manage tables →</span>
          </button>
        </div>

        <div className="bg-zinc-900 border border-zinc-800/80 p-5 rounded-2xl shadow-xl flex flex-col justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Active Bookings</p>
            <h3 className="text-3xl font-bold mt-2 text-emerald-500">{activeReservations} Tables</h3>
          </div>
          <button onClick={() => setActiveTab('reservations')} className="mt-4 text-xs font-medium text-emerald-500 hover:text-emerald-400 text-left flex items-center space-x-1">
            <span>View timeline →</span>
          </button>
        </div>

        <div className="bg-zinc-900 border border-zinc-800/80 p-5 rounded-2xl shadow-xl flex flex-col justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Fulfilled & Settled</p>
            <h3 className="text-3xl font-bold mt-2 text-teal-400">{totalPaidBookings} Orders</h3>
          </div>
          <button onClick={() => setActiveTab('billing')} className="mt-4 text-xs font-medium text-emerald-500 hover:text-emerald-400 text-left flex items-center space-x-1">
            <span>Process cash counter →</span>
          </button>
        </div>

        <div className="bg-zinc-900 border border-zinc-800/80 p-5 rounded-2xl shadow-xl flex flex-col justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Unbilled Order Book Pipeline</p>
            <h3 className="text-3xl font-bold mt-2 text-cyan-500">{estimatedRevenue.toLocaleString()} RWF</h3>
          </div>
          <button onClick={() => setActiveTab('reports')} className="mt-4 text-xs font-medium text-emerald-500 hover:text-emerald-400 text-left flex items-center space-x-1">
            <span>Check statements →</span>
          </button>
        </div>
      </div>

      {/* Interactive Quick-Action Panel & Operations Map */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Dynamic Floor Grid Visualizer */}
        <div className="lg:col-span-2 bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
          <div className="flex justify-between items-center mb-6">
            <div>
              <h3 className="text-lg font-bold text-white">Live Dining Room Blueprint</h3>
              <p className="text-xs text-zinc-400">Click on an active table map module below to instantly dispatch actions.</p>
            </div>
            <span className="text-xs px-2.5 py-1 rounded-full font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 animate-pulse">
              Live Monitoring
            </span>
          </div>

          {totalTables === 0 ? (
            <div className="h-48 border border-dashed border-zinc-800 rounded-xl flex flex-col items-center justify-center text-zinc-500 text-sm">
              No tables registered on the system layout.
              <button onClick={() => setActiveTab('tables')} className="mt-3 text-xs bg-zinc-800 text-zinc-200 px-3 py-1.5 rounded-lg border border-zinc-700 hover:bg-zinc-700">Add First Table</button>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
              {tablesList.map((table) => {
                const currentBooking = reservationsList.find(r => String(r.TableNumber) === String(table.TableNumber) && r.Status === 'Active');
                const isOccupied = !!currentBooking;

                return (
                  <div 
                    key={table.TableNumber} 
                    className={`p-4 rounded-xl border transition-all relative group flex flex-col justify-between h-28 ${
                      isOccupied 
                        ? 'bg-emerald-950/20 border-emerald-600/40 hover:border-emerald-500' 
                        : 'bg-zinc-950/40 border-zinc-800 hover:border-zinc-700'
                    }`}
                  >
                    <div className="flex justify-between items-start">
                      <span className="font-mono text-xs text-zinc-500">T-{table.TableNumber}</span>
                      <span className={`w-2 h-2 rounded-full ${isOccupied ? 'bg-emerald-500 shadow-md shadow-emerald-500/50' : 'bg-zinc-800'}`} />
                    </div>

                    <div className="mt-2">
                      <p className="text-sm font-bold tracking-tight text-zinc-200 truncate">{table.CustomerName || 'Empty Table'}</p>
                      <p className="text-[11px] text-zinc-400 truncate mt-0.5">
                        {isOccupied ? `Waiter: ${table.WaiterName || 'N/A'}` : `${table.GuestCount || 0} Seat Capacity`}
                      </p>
                    </div>

                    {/* Interactive Operational Hot-Swap Overlays */}
                    <div className="absolute inset-0 bg-zinc-950/90 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center space-x-2 px-2">
                      {isOccupied ? (
                        <>
                          <button onClick={() => setActiveTab('orders')} className="bg-emerald-500 text-zinc-950 px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider hover:bg-emerald-400">
                            + Order
                          </button>
                          <button onClick={() => setActiveTab('billing')} className="bg-zinc-800 border border-zinc-700 text-zinc-200 px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider hover:bg-zinc-700">
                            Bill
                          </button>
                        </>
                      ) : (
                        <button onClick={() => setActiveTab('reservations')} className="bg-zinc-800 border border-zinc-700 text-emerald-500 px-3 py-1 rounded text-[10px] font-bold uppercase tracking-wider hover:bg-zinc-700 w-full">
                          Assign Guest
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Workflow Routing Feed */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6 flex flex-col justify-between">
          <div>
            <h3 className="text-lg font-bold text-white mb-1">Quick Actions Gateway</h3>
            <p className="text-xs text-zinc-400 mb-6">Unified shortcuts link to key functional subsystems instantly.</p>
            
            <div className="space-y-3">
              <button onClick={() => setActiveTab('reservations')} className="w-full p-3 text-left bg-zinc-950/50 border border-zinc-800 hover:border-zinc-700 rounded-xl flex items-center justify-between group transition-all">
                <div>
                  <h4 className="text-xs font-bold text-zinc-200 uppercase tracking-wide">Register New Visit</h4>
                  <p className="text-[11px] text-zinc-500 mt-0.5">Bind customer context records onto active layouts.</p>
                </div>
                <span className="text-zinc-600 group-hover:text-emerald-500 transition-colors">→</span>
              </button>

              <button onClick={() => setActiveTab('orders')} className="w-full p-3 text-left bg-zinc-950/50 border border-zinc-800 hover:border-zinc-700 rounded-xl flex items-center justify-between group transition-all">
                <div>
                  <h4 className="text-xs font-bold text-zinc-200 uppercase tracking-wide">Punch Ticket Orders</h4>
                  <p className="text-[11px] text-zinc-500 mt-0.5">Route kitchen items directly to target customer tables.</p>
                </div>
                <span className="text-zinc-600 group-hover:text-emerald-500 transition-colors">→</span>
              </button>

              <button onClick={() => setActiveTab('billing')} className="w-full p-3 text-left bg-zinc-950/50 border border-zinc-800 hover:border-zinc-700 rounded-xl flex items-center justify-between group transition-all">
                <div>
                  <h4 className="text-xs font-bold text-zinc-200 uppercase tracking-wide">Generate POS Invoices</h4>
                  <p className="text-[11px] text-zinc-500 mt-0.5">Calculate subtotals, append print commands, lock files.</p>
                </div>
                <span className="text-zinc-600 group-hover:text-emerald-500 transition-colors">→</span>
              </button>
            </div>
          </div>

          <div className="mt-6 pt-4 border-t border-zinc-800/60 text-center">
            <p className="text-[10px] text-zinc-500 uppercase font-mono tracking-widest">Taste of Rwanda • Operations 2026</p>
          </div>
        </div>
      </div>
    </div>
  );
}

// --- MAIN RUNTIME APPLICATION MODULE ---
function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [activeTab, setActiveTab] = useState('dashboard');
  const [username, setUsername] = useState('');

  const [tablesList, setTablesList] = useState([]);
  const [reservationsList, setReservationsList] = useState([]);
  const [reportData, setReportData] = useState(null);

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

  useEffect(() => {
    if (isAuthenticated) {
      loadSystemData();
    }
  }, [isAuthenticated, activeTab]);

  const checkSession = async () => {
    try {
      const res = await axios.get(`${API_URL}/session`);
      if (res.data.loggedIn) {
        setIsAuthenticated(true);
        setUsername(res.data.username);
      }
    } catch (err) {
      setIsAuthenticated(false);
    }
  };

  const loadSystemData = async () => {
    try {
      const tRes = await axios.get(`${API_URL}/tables`);
      setTablesList(tRes.data);

      const rRes = await axios.get(`${API_URL}/reservations`);
      setReservationsList(rRes.data);

      if (activeTab === 'reports') {
        const repRes = await axios.get(`${API_URL}/reports/daily`);
        setReportData(repRes.data);
      }
    } catch (err) {
      console.error('Data layer tracking anomaly recorded.', err);
    }
  };

  const handleLogout = async () => {
    await axios.post(`${API_URL}/logout`);
    setIsAuthenticated(false);
  };

  if (!isAuthenticated) {
    return <Login onLoginSuccess={() => checkSession()} API_URL={API_URL} />;
  }

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 font-sans">
      <header className="border-b border-zinc-900 bg-zinc-950/80 backdrop-blur sticky top-0 z-50 px-6 py-4 flex justify-between items-center">
        <div className="flex items-center space-x-3">
          <div className="h-9 w-9 rounded-xl bg-gradient-to-tr from-emerald-500 to-teal-600 flex items-center justify-center font-black text-black text-lg">TR</div>
          <span className="text-xl font-bold tracking-tight bg-gradient-to-r from-white to-zinc-400 bg-clip-text text-transparent">Taste of Rwanda RRBMS</span>
        </div>
        <div className="flex items-center space-x-4">
          <span className="text-xs bg-zinc-900 border border-zinc-800 px-3 py-1.5 rounded-lg text-zinc-400">Operator: <b className="text-zinc-200">{username}</b></span>
          <button onClick={handleLogout} className="bg-rose-950/40 hover:bg-rose-900/60 border border-rose-900/50 text-rose-400 px-3 py-1.5 rounded-lg text-xs transition-colors">Sign Out</button>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Navigation Bar Header */}
        <nav className="flex flex-wrap gap-2 border-b border-zinc-900 pb-4 mb-8">
          {['dashboard', 'tables', 'reservations', 'orders', 'billing', 'reports'].map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-2 rounded-xl text-sm font-medium transition-all uppercase tracking-wider ${
                activeTab === tab ? 'bg-gradient-to-r from-emerald-500 to-teal-600 text-white shadow-md' : 'text-zinc-400 hover:text-white hover:bg-zinc-900/50'
              }`}
            >
              {tab}
            </button>
          ))}
        </nav>

        {/* Workspace Display Viewports */}
        <main>
          {activeTab === 'dashboard' && (
            <DashboardOverview 
              tablesList={tablesList} 
              reservationsList={reservationsList} 
              setActiveTab={setActiveTab} 
            />
          )}
          {activeTab === 'tables' && <TablePage tablesList={tablesList} loadSystemData={loadSystemData} API_URL={API_URL} />}
          {activeTab === 'reservations' && <ReservationPage tablesList={tablesList} reservationsList={reservationsList} loadSystemData={loadSystemData} API_URL={API_URL} />}
          {activeTab === 'orders' && <OrderPage API_URL={API_URL} />}
          {activeTab === 'billing' && <BillingPage reservationsList={reservationsList} loadSystemData={loadSystemData} API_URL={API_URL} />}
          {activeTab === 'reports' && <ReportPage reportData={reportData} />}
        </main>
      </div>
    </div>
  );
}

export default App;