import { Switch, Route, useLocation } from "wouter";
import { useState, useEffect } from "react";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { AuthProvider, useAuth } from "@/hooks/use-auth";
import Dashboard from "@/pages/dashboard";
import TelkomClients from "@/pages/telkom-clients";
import TelkomSmart from "@/pages/telkom-smart";
import StandardClients from "@/pages/standard-clients";
import MTNMobile from "@/pages/mtn-mobile";
import MTNFixed from "@/pages/mtn-fixed";
import Axxess from "@/pages/axxess";
import AxxessTelkom from "@/pages/axxess-telkom";
import AxxessFibre from "@/pages/axxess-fibre";
import OpenServeFibre from "@/pages/openserve-fibre";
import Search from "@/pages/search";
import Reports from "@/pages/reports";
import Changelog from "@/pages/changelog";
import SystemUsers from "@/pages/system-users";
import StaffNotifications from "@/pages/staff-notifications";
import ApiKeys from "@/pages/api-keys";
import ActionLog from "@/pages/action-log";
import Login from "@/pages/login";
import NotFound from "@/pages/not-found";
import Sidebar from "@/components/sidebar";
import ChangelogModal from "@/components/changelog-modal";
import { Loader2 } from "lucide-react";
import { VERSION } from "@shared/version";

function Router() {
  const { isAuthenticated, isLoading, user } = useAuth();
  const [location, navigate] = useLocation();
  const [showChangelogModal, setShowChangelogModal] = useState(false);

  // Redirect authenticated users away from login page
  useEffect(() => {
    if (isAuthenticated && location === '/login') {
      navigate('/');
    }
  }, [isAuthenticated, location, navigate]);

  // Check if user should see the changelog modal on login
  useEffect(() => {
    if (isAuthenticated && user) {
      const lastSeenVersionKey = `changelog_seen_${user.id}_${VERSION}`;
      const hasSeenLatestVersion = localStorage.getItem(lastSeenVersionKey);
      
      if (!hasSeenLatestVersion) {
        setShowChangelogModal(true);
      }
    }
  }, [isAuthenticated, user]);

  const handleChangelogModalClose = () => {
    if (user) {
      const lastSeenVersionKey = `changelog_seen_${user.id}_${VERSION}`;
      localStorage.setItem(lastSeenVersionKey, 'true');
    }
    setShowChangelogModal(false);
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <Switch>
        <Route path="/login" component={Login} />
        <Route component={Login} />
      </Switch>
    );
  }

  return (
    <>
      <div className="flex h-screen bg-gray-50">
        <Sidebar />
        <div className="flex-1 flex flex-col overflow-hidden">
          <Switch>
            <Route path="/" component={Dashboard} />
            <Route path="/telkom" component={TelkomClients} />
            <Route path="/telkom-smart" component={TelkomSmart} />
            <Route path="/mtn-mobile" component={MTNMobile} />
            <Route path="/mtn-fixed" component={MTNFixed} />
            <Route path="/axxess" component={Axxess} />
            <Route path="/axxess-telkom" component={AxxessTelkom} />
            <Route path="/axxess-fibre" component={AxxessFibre} />
            <Route path="/openserve-fibre" component={OpenServeFibre} />
            <Route path="/standard" component={StandardClients} />
            <Route path="/search" component={Search} />
            <Route path="/reports" component={Reports} />
            <Route path="/changelog" component={Changelog} />
            <Route path="/system-users" component={SystemUsers} />
            <Route path="/staff-notifications" component={StaffNotifications} />
            <Route path="/api-keys" component={ApiKeys} />
            <Route path="/action-log" component={ActionLog} />
            <Route component={NotFound} />
          </Switch>
        </div>
      </div>
      
      <ChangelogModal
        isOpen={showChangelogModal}
        onClose={handleChangelogModalClose}
        version={VERSION}
      />
    </>
  );
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <TooltipProvider>
          <Router />
          <Toaster />
        </TooltipProvider>
      </AuthProvider>
    </QueryClientProvider>
  );
}

export default App;
