import { useEffect } from "react";
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from "react-router-dom";
import { listen } from "@tauri-apps/api/event";
import RecordingView from "./views/RecordingView";
import EditorView from "./views/EditorView";
import LibraryView from "./views/LibraryView";
import OverlayView from "./views/OverlayView";
import RegionSelectorView from "./views/RegionSelectorView";
import LayoutPrototypeView from "./views/LayoutPrototypeView";
import { ShortcutProvider } from "./contexts/ShortcutContext";
import ShortcutHelp from "./components/ShortcutHelp";
import { initializeWorkflowMetricsStore } from "./lib/usageMetrics";

// Component to handle navigation events from the overlay window
function NavigationEventListener() {
    const navigate = useNavigate();

    useEffect(() => {
        let cleanup: (() => void) | undefined;

        const setupListeners = async () => {
            const { getCurrentWindow } = await import("@tauri-apps/api/window");
            const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");

            // Check window label, not path - this is reliable even during async routing
            const currentWindow = getCurrentWindow();
            if (currentWindow.label !== "main") {
                return; // Only main window handles navigation events
            }

            const unlistenEditor = await listen<{ sessionId: string }>(
                "navigate-to-editor",
                async (event) => {
                    // Get main window by label, not getCurrentWindow()
                    const mainWindow = await WebviewWindow.getByLabel("main");
                    if (mainWindow) {
                        await mainWindow.show();
                        await mainWindow.setFocus();
                    }
                    navigate(`/editor/${event.payload.sessionId}`);
                }
            );

            const unlistenRecord = await listen("navigate-to-record", async () => {
                const mainWindow = await WebviewWindow.getByLabel("main");
                if (mainWindow) {
                    await mainWindow.show();
                    await mainWindow.setFocus();
                }
                navigate("/record");
            });

            const unlistenLibrary = await listen("navigate-to-library", async () => {
                const mainWindow = await WebviewWindow.getByLabel("main");
                if (mainWindow) {
                    await mainWindow.show();
                    await mainWindow.setFocus();
                }
                navigate("/library");
            });

            cleanup = () => {
                unlistenEditor();
                unlistenRecord();
                unlistenLibrary();
            };
        };

        setupListeners();

        return () => {
            cleanup?.();
        };
    }, [navigate]);

    return null;
}

function AppRoutes() {
    return (
        <>
            <NavigationEventListener />
            <Routes>
                <Route path="/" element={<Navigate to="/library" replace />} />
                <Route path="/library" element={<LibraryView />} />
                <Route path="/record" element={<RecordingView />} />
                <Route path="/editor/:sessionId" element={<EditorView />} />
                <Route path="/overlay" element={<OverlayView />} />
                <Route path="/region-selector" element={<RegionSelectorView />} />
                <Route path="/layout-prototype" element={<LayoutPrototypeView />} />
                {/* Future routes: /permissions, /upload/:sessionId, /share/:token */}
            </Routes>
        </>
    );
}

function App() {
    useEffect(() => {
        void initializeWorkflowMetricsStore();
    }, []);

    return (
        <ShortcutProvider>
            <BrowserRouter>
                <AppRoutes />
            </BrowserRouter>
            <ShortcutHelp />
        </ShortcutProvider>
    );
}

export default App;
