// File Path: monorepo/native/desktop/maplefile/frontend/src/App.jsx
import { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
  useNavigate,
} from "react-router-dom";
import {
  IsLoggedIn,
  HasStoredPassword,
  DecryptLoginChallenge,
} from "../wailsjs/go/app/Application";
import PasswordPrompt from "./components/PasswordPrompt";
import "./App.css";

// Anonymous Pages
import IndexPage from "./pages/Anonymous/Index/IndexPage";
import Register from "./pages/Anonymous/Register/Register";
import RecoveryCode from "./pages/Anonymous/Register/RecoveryCode";
import VerifyEmail from "./pages/Anonymous/Register/VerifyEmail";
import VerifySuccess from "./pages/Anonymous/Register/VerifySuccess";
import RequestOTT from "./pages/Anonymous/Login/RequestOTT";
import VerifyOTT from "./pages/Anonymous/Login/VerifyOTT";
import CompleteLogin from "./pages/Anonymous/Login/CompleteLogin";
import SessionExpired from "./pages/Anonymous/Login/SessionExpired";
import InitiateRecovery from "./pages/Anonymous/Recovery/InitiateRecovery";
import VerifyRecovery from "./pages/Anonymous/Recovery/VerifyRecovery";
import CompleteRecovery from "./pages/Anonymous/Recovery/CompleteRecovery";

// User Pages
import Dashboard from "./pages/User/Dashboard/Dashboard";
import FileManagerIndex from "./pages/User/FileManager/FileManagerIndex";
import CollectionCreate from "./pages/User/FileManager/Collections/CollectionCreate";
import CollectionDetails from "./pages/User/FileManager/Collections/CollectionDetails";
import CollectionEdit from "./pages/User/FileManager/Collections/CollectionEdit";
import CollectionShare from "./pages/User/FileManager/Collections/CollectionShare";
import FileUpload from "./pages/User/FileManager/Files/FileUpload";
import FileDetails from "./pages/User/FileManager/Files/FileDetails";
import MeDetail from "./pages/User/Me/MeDetail";
import DeleteAccount from "./pages/User/Me/DeleteAccount";
import BlockedUsers from "./pages/User/Me/BlockedUsers";
import TagCreate from "./pages/User/Tags/TagCreate";
import TagEdit from "./pages/User/Tags/TagEdit";
import TagSearch from "./pages/User/Tags/TagSearch";
import FullTextSearch from "./pages/User/Search/FullTextSearch";

function AppContent() {
  const [authState, setAuthState] = useState({
    isLoggedIn: null, // null = checking, true/false = known
    hasPassword: null, // Does RAM have password?
    needsPassword: false, // Should we show password prompt?
    loading: true,
    email: null,
  });

  const navigate = useNavigate();

  useEffect(() => {
    // Wait for Wails runtime to be ready before checking auth
    let attempts = 0;
    const maxAttempts = 50; // 5 seconds max
    let isCancelled = false;

    const checkWailsReady = () => {
      if (isCancelled) return;

      if (window.go && window.go.app && window.go.app.Application) {
        checkAuthState();
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkWailsReady, 100);
      } else {
        // Timeout - assume not logged in
        console.error("Wails runtime failed to initialize");
        setAuthState({
          isLoggedIn: false,
          hasPassword: false,
          needsPassword: false,
          loading: false,
          email: null,
        });
      }
    };

    checkWailsReady();

    return () => {
      isCancelled = true;
    };
  }, []);

  async function checkAuthState() {
    try {
      // Double-check Wails runtime is available
      if (!window.go || !window.go.app || !window.go.app.Application) {
        throw new Error("Wails runtime not available");
      }

      // Step 1: Check if user is logged in (session exists)
      const loggedIn = await IsLoggedIn();

      if (!loggedIn) {
        // Not logged in → show login screen
        setAuthState({
          isLoggedIn: false,
          hasPassword: false,
          needsPassword: false,
          loading: false,
          email: null,
        });
        return;
      }

      // Step 2: User is logged in, check for stored password
      const hasPassword = await HasStoredPassword();

      if (hasPassword) {
        // Password is stored in RAM → all good
        setAuthState({
          isLoggedIn: true,
          hasPassword: true,
          needsPassword: false,
          loading: false,
          email: null, // We could fetch session info if needed
        });
      } else {
        // No password in RAM → need to prompt
        setAuthState({
          isLoggedIn: true,
          hasPassword: false,
          needsPassword: true,
          loading: false,
          email: null, // PasswordPrompt will get this from session
        });
      }
    } catch (error) {
      console.error("Auth state check failed:", error);
      setAuthState({
        isLoggedIn: false,
        hasPassword: false,
        needsPassword: false,
        loading: false,
        email: null,
      });
    }
  }

  const handlePasswordVerified = async (password) => {
    // For now, we'll assume verification happens in the PasswordPrompt
    // The password is stored by StorePasswordForSession in the component

    // Update state to indicate password is now available
    setAuthState({
      ...authState,
      hasPassword: true,
      needsPassword: false,
    });

    // Navigate to dashboard
    navigate("/dashboard");

    return true; // Password is valid
  };

  // Show loading screen while checking auth
  if (authState.loading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
          background: "#f8f9fa",
        }}
      >
        <div style={{ textAlign: "center" }}>
          <h2>MapleFile</h2>
          <p style={{ color: "#666" }}>Loading...</p>
        </div>
      </div>
    );
  }

  // Show password prompt if logged in but no password
  if (authState.isLoggedIn && authState.needsPassword) {
    return (
      <PasswordPrompt
        email={authState.email || "Loading..."}
        onPasswordVerified={handlePasswordVerified}
      />
    );
  }

  return (
    <Routes>
      {/* Anonymous/Public Routes */}
      <Route path="/" element={<IndexPage />} />

      {/* Registration Flow */}
      <Route path="/register" element={<Register />} />
      <Route path="/register/recovery" element={<RecoveryCode />} />
      <Route path="/register/verify-email" element={<VerifyEmail />} />
      <Route path="/register/verify-success" element={<VerifySuccess />} />

      {/* Login Flow */}
      <Route path="/login" element={<RequestOTT />} />
      <Route path="/login/verify-ott" element={<VerifyOTT />} />
      <Route path="/login/complete" element={<CompleteLogin />} />
      <Route path="/session-expired" element={<SessionExpired />} />

      {/* Recovery Flow */}
      <Route path="/recovery" element={<InitiateRecovery />} />
      <Route path="/recovery/initiate" element={<InitiateRecovery />} />
      <Route path="/recovery/verify" element={<VerifyRecovery />} />
      <Route path="/recovery/complete" element={<CompleteRecovery />} />

      {/* Authenticated User Routes */}
      <Route path="/dashboard" element={<Dashboard />} />

      {/* File Manager Routes */}
      <Route path="/file-manager" element={<FileManagerIndex />} />
      <Route
        path="/file-manager/collections/create"
        element={<CollectionCreate />}
      />
      <Route
        path="/file-manager/collections/:collectionId"
        element={<CollectionDetails />}
      />
      <Route
        path="/file-manager/collections/:collectionId/edit"
        element={<CollectionEdit />}
      />
      <Route
        path="/file-manager/collections/:collectionId/share"
        element={<CollectionShare />}
      />
      <Route path="/file-manager/upload" element={<FileUpload />} />
      <Route path="/file-manager/files/:fileId" element={<FileDetails />} />
      {/* Export moved to Profile page - redirect old route */}
      <Route path="/file-manager/export" element={<Navigate to="/me?tab=export" replace />} />

      {/* User Profile Routes */}
      <Route path="/me" element={<MeDetail />} />
      <Route path="/profile" element={<MeDetail />} />
      <Route path="/me/delete-account" element={<DeleteAccount />} />
      <Route path="/me/blocked-users" element={<BlockedUsers />} />

      {/* Tags Routes */}
      <Route path="/tags/search" element={<TagSearch />} />
      <Route path="/me/tags/create" element={<TagCreate />} />
      <Route path="/me/tags/:tagId/edit" element={<TagEdit />} />

      {/* Search Routes */}
      <Route path="/search" element={<FullTextSearch />} />

      {/* Catch-all route */}
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

function App() {
  return (
    <Router>
      <AppContent />
    </Router>
  );
}

export default App;
