import React, { useContext } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, AuthContext } from './contexts/AuthContext';
import Login from './components/Auth/Login';
import Register from './components/Auth/Register';
import LandingPage from './pages/LandingPage';

const PrivateRoute = ({ children }) => {
  const { user } = useContext(AuthContext);
  return user ? children : <Navigate to="/login" />;
};

import EntryForm from './components/TimeEntry/EntryForm';
import TimeList from './components/TimeEntry/TimeList';
import BalanceCard from './components/TimeEntry/BalanceCard';
import RedeemForm from './components/TimeEntry/RedeemForm';
import ProfileSettings from './components/Profile/ProfileSettings';
import SupervisorDashboard from './components/Supervisor/SupervisorDashboard';
import GoCLayout from './components/Layout/GoCLayout';
import { LanguageProvider } from './contexts/LanguageContext';
import { pb } from './lib/pocketbase';
import { useState, useEffect } from 'react';

const Dashboard = () => {
  const { user, logout } = useContext(AuthContext);
  const [entries, setEntries] = useState([]);
  const [balance, setBalance] = useState(0);
  const [refresh, setRefresh] = useState(0);

  const loadData = async () => {
    try {
      // Load recent entries
      const records = await pb.collection('time_entries').getList(1, 50, {
        sort: '-date',
      });
      setEntries(records.items);

      // Load balance (banked hours)
      const allBanked = await pb.collection('time_entries').getFullList({
        filter: 'is_banked = true',
        requestKey: null // Disable auto-cancellation to ensure it runs
      });
      const total = allBanked.reduce((acc, curr) => acc + (curr.calculated_hours || 0), 0);
      setBalance(total);

    } catch (error) {
      console.error("Error loading data", error);
    }
  };

  useEffect(() => {
    loadData();
  }, [refresh]);

  const handleEntryAdded = () => {
    setRefresh(prev => prev + 1);
  };

  return (
    <GoCLayout>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          {/* Supervisor Dashboard (Only visible if is_supervisor) */}
          {user.is_supervisor && (
            <SupervisorDashboard user={user} />
          )}

          <EntryForm onEntryAdded={handleEntryAdded} />
          <TimeList entries={entries} />
        </div>
        <div className="space-y-6">
          <BalanceCard balance={balance} />
          <RedeemForm onRedeem={handleEntryAdded} />
          <ProfileSettings user={user} />
        </div>
      </div>
    </GoCLayout>
  );
};

function App() {
  return (
    <AuthProvider>
      <LanguageProvider>
        <Router>
          <Routes>
            <Route path="/" element={<LandingPage />} />
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route
              path="/dashboard"
              element={
                <PrivateRoute>
                  <Dashboard />
                </PrivateRoute>
              }
            />
          </Routes>
        </Router>
      </LanguageProvider>
    </AuthProvider>
  );
}

export default App;
