import React, { lazy, useEffect, useState } from 'react';
import { Routes, Route, HashRouter, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { onSignInSuccess, setLoggedInUser, setToken, setXWpNonce } from "./store/auth/sessionSlice";
import { fetchTask, openTaskEditDrawer, closeTaskEditDrawer } from "./components/Settings/store/taskSlice";
import { setUser } from "./store/auth/userSlice";
import { jwtDecode } from "jwt-decode";
import appConfig from "./configs/app.config";
import Cookies from "js-cookie";
import { Center, Drawer, LoadingOverlay } from '@mantine/core';
const EditTaskDrawer = lazy(() => import('./components/Elements/Project/TasksElements/EditTaskDrawer'));

// Always-loaded: small route guards and auth page
import Login from "./components/Login";
import Header from './components/Header';
import ProtectedRoute from "./route/ProtectedRoute";
import PublicRoute from "./route/PublicRoute";
import PremiumRoute from "./route/PremiumRoute";
import WhiteboardRoute from './route/WhiteboardRoute';
import NotFound from './components/NotFound';

// Phase 4 — guard for /time-tracker* routes. If the user has no `timetracker-access`
// on any project AND is not superadmin, redirect to /dashboard. Same "any project" check
// as the top-nav link in Header.jsx.
const TimeTrackerRouteGuard = ({ children }) => {
    const navigate = useNavigate();
    const hasAnyAccess = useSelector(state => {
        const user = state.auth?.session?.loggedInUser;
        if (!user) return false;
        if (user.is_superadmin) return true;
        const projects = state.auth?.permissions?.projects || {};
        for (const id in projects) {
            const list = projects[id]?.permissions;
            if (Array.isArray(list) && list.includes('timetracker-access')) return true;
        }
        return false;
    });
    useEffect(() => {
        if (!hasAnyAccess) {
            navigate('/dashboard', { replace: true });
        }
    }, [hasAnyAccess, navigate]);
    if (!hasAnyAccess) return null;
    return children;
};

// Lazy-loaded: heavy feature chunks split by route
const Dashboard               = lazy(() => import('./components/Dashboard'));
const MyTask                  = lazy(() => import('./components/MyTask'));
const MyZen                   = lazy(() => import('./components/MyZen'));

const Profile                 = lazy(() => import('./components/Profile/Profile'));
const ProfileEdit             = lazy(() => import('./components/Profile/ProfileEdit'));
const ResetPassword           = lazy(() => import('./components/Profile/ResetPassword'));
const ForgetPassword          = lazy(() => import('./components/Profile/ForgetPassword'));
const ChangePassword          = lazy(() => import('./components/Login/ChangePassword'));

const SettingsPageV3          = lazy(() => import('./components/Settings/v3/SettingsPageV3'));

const ProjectDetails                      = lazy(() => import('./components/Elements/Project/ProjectDetails'));
const ProjectDetailsList                  = lazy(() => import('./components/Elements/Project/ProjectDetailsList'));
const ProjectDetailsBoard                 = lazy(() => import('./components/Elements/Project/ProjectDetailsBorad'));
const ProjectDetailsCalendar              = lazy(() => import('./components/Elements/Project/ProjectDetailsCalendar'));
const ProjectDetailsGanttChart            = lazy(() => import('./components/Elements/Project/ProjectDetailsGanttChart'));
const ProjectDetailsReport                = lazy(() => import('./components/Elements/Project/ProjectDetailsReport'));
const ProjectDetailsListSectionByPriority = lazy(() => import('./components/Elements/Project/ProjectDetailsListSectionByPriority'));
const ProjectDetailsListSectionByStatus   = lazy(() => import('./components/Elements/Project/ProjectDetailsListSectionByStatus'));
const ProjectDetailsListSectionByMember   = lazy(() => import('./components/Elements/Project/ProjectDetailsListSectionByMember'));
const ProjectDetailsListSectionByDueDate  = lazy(() => import('./components/Elements/Project/ProjectDetailsListSectionByDueDate'));
const ProjectDetailsBoardSectionByPriority = lazy(() => import('./components/Elements/Project/ProjectDetailsBoardSectionByPriority'));
const ProjectDetailsBoardSectionByStatus   = lazy(() => import('./components/Elements/Project/ProjectDetailsBoardSectionByStatus'));
const ProjectDetailsBoardSectionByMember   = lazy(() => import('./components/Elements/Project/ProjectDetailsBoardSectionByMember'));
const ProjectDetailsBoardSectionByDueDate  = lazy(() => import('./components/Elements/Project/ProjectDetailsBoardSectionByDueDate'));
const WhiteboardOutdatedFallback           = lazy(() => import('./components/Elements/Project/WhiteboardOutdatedFallback'));

const AppRoutes = () => {

    const dispatch = useDispatch()

    useEffect(() => {
        if (appLocalizer?.is_admin) {
            if (appLocalizer.userResponse.data.token) {
                const user_token = appLocalizer.userResponse.data.token
                const nonce = appLocalizer.userResponse.data.nonce
                dispatch(onSignInSuccess(user_token))
                dispatch(setToken(user_token))
                dispatch(setXWpNonce(nonce))
                const decode_token = jwtDecode(user_token)
                if (decode_token.iss === appConfig.liveSiteUrl) {

                    const userData = decode_token.data;

                    const user = {
                        "authority": userData.roles,
                        "loggedUserId": userData.user_id,
                        "name": userData.name,
                        "email": userData.email,
                        "roles": userData.roles,
                        "llc_roles": userData.llc_roles,
                        "llc_permissions": userData.llc_permissions,
                        "avatar": userData.avatar,
                        "is_superadmin": userData.is_superadmin ?? false,
                        "project_roles": userData.project_roles || []
                    }
                    dispatch(setLoggedInUser(user || {}))
                    Cookies.set('user_id', userData.user_id);
                    dispatch(
                        setUser(
                            user || {
                                avatar: '',
                                loggedUserId: '',
                                name: '',
                                authority: [],
                                email: '',
                                roles: [],
                                llc_roles: [],
                                llc_permissions: [],
                            }
                        )
                    )
                }
            }

        }


    }, [dispatch]);

    const { signedIn, loggedInUser } = useSelector((state) => state.auth.session);
    const { taskEditDrawerOpen, task: editTask } = useSelector((state) => state.settings.task);
    const whiteboardAddonState = useSelector((state) => state.settings?.setting?.whiteboardAddonState);
    const handlerCloseTaskEditDrawer = () => dispatch(closeTaskEditDrawer());

    useEffect(() => {
        window.loggedInUser = loggedInUser;
        if (loggedInUser) {
            window.dispatchEvent(new CustomEvent('lazytasksUserReady', { detail: loggedInUser }));
        }
    }, [loggedInUser]);

    // Handle "view task" requests dispatched by addon bundles (e.g. TimeLogsGrouped)
    // that cannot access the main plugin's Redux store directly.
    useEffect(() => {
        const handler = (e) => {
            const { taskId } = e.detail
            dispatch(fetchTask({ id: taskId }))
            dispatch(openTaskEditDrawer())
        }
        window.addEventListener('lazytasks:openTaskDrawer', handler)
        return () => window.removeEventListener('lazytasks:openTaskDrawer', handler)
    }, [dispatch]);

    const [premiumRoutes, setPremiumRoutes] = useState([]);
    const [whiteboardRoutes, setWhiteboardRoutes] = useState([]);
    const [timeTrackerRoutes, setTimeTrackerRoutes] = useState([]);
    const [performanceRoutes, setPerformanceRoutes] = useState([]);
    const [routesLoaded, setRoutesLoaded] = useState(false);
    useEffect(() => {
        if (window.lazytaskPremium) {
            setPremiumRoutes(window.lazytaskPremium.premiumAppRoutes || []);
        }
        if (window.lazytasksWhiteboard) {
            setWhiteboardRoutes(window.lazytasksWhiteboard.whiteboardRoutes || []);
        }
        if (window.lazytasksTimeTracker) {
            setTimeTrackerRoutes(window.lazytasksTimeTracker.timeTrackerRoutes || []);
        }
        if (window.lazytasksPerformance) {
            setPerformanceRoutes(window.lazytasksPerformance.performanceRoutes || []);
        }
        setRoutesLoaded(true);

        const onWhiteboardReady = () => {
            setWhiteboardRoutes(window.lazytasksWhiteboard?.whiteboardRoutes || []);
        };
        const onTimeTrackerReady = () => {
            setTimeTrackerRoutes(window.lazytasksTimeTracker?.timeTrackerRoutes || []);
        };
        const onPerformanceReady = () => {
            setPerformanceRoutes(window.lazytasksPerformance?.performanceRoutes || []);
        };

        if (!window.lazytasksWhiteboard) {
            window.addEventListener('lazytasksWhiteboardReady', onWhiteboardReady);
        }
        if (!window.lazytasksTimeTracker) {
            window.addEventListener('lazytasksTimeTrackerReady', onTimeTrackerReady);
        }
        if (!window.lazytasksPerformance) {
            window.addEventListener('lazytasksPerformanceReady', onPerformanceReady);
        }

        return () => {
            window.removeEventListener('lazytasksWhiteboardReady', onWhiteboardReady);
            window.removeEventListener('lazytasksTimeTrackerReady', onTimeTrackerReady);
            window.removeEventListener('lazytasksPerformanceReady', onPerformanceReady);
        };
    }, []);

    // Show loader until routes are loaded
    if (!routesLoaded) {
        return (
            <Center style={{ height: '100vh' }}>
                <LoadingOverlay visible={true} zIndex={1000} overlayProps={{ radius: "sm", blur: 2 }} />
            </Center>
        );
    }

    return (
        <>
            <HashRouter>
                <NavigateBridge />
                <Routes>
                    {/*<Route path="/" element={<ProtectedRoute authenticated={signedIn} />}>*/}
                    <Route path="/" element={<ProtectedWithHeader signedIn={signedIn} />}>
                        {/*<Route path="/" element={<Dashboard />} />*/}

                        <Route path="/dashboard" element={<Dashboard />} />
                        <Route path="/my-task" element={<MyTask />} />
                        <Route path="/my-zen" element={<MyZen />} />
                        <Route path="/profile" element={<Profile />} />
                        <Route path="/profile/:id" element={<ProfileEdit />} />
                        <Route path="/resetpassword" element={<ResetPassword />} />
                        <Route path="/v3/settings" element={<SettingsPageV3 />} />

                        {premiumRoutes.length > 0 && premiumRoutes.map((route, index) => (
                            <Route
                                key={route.key + index}
                                path={route.path}
                                element={
                                    <PremiumRoute
                                        routeKey={route.key}
                                        component={route.component}
                                        {...route.meta}
                                    />
                                }
                            />
                        ))}

                        {timeTrackerRoutes.map((route) => {
                            const RouteComponent = route.component;
                            return (
                                <Route
                                    key={route.key}
                                    path={route.path}
                                    element={
                                        <React.Suspense fallback={null}>
                                            <TimeTrackerRouteGuard>
                                                <RouteComponent />
                                            </TimeTrackerRouteGuard>
                                        </React.Suspense>
                                    }
                                />
                            );
                        })}

                        {performanceRoutes.map((route) => {
                            const RouteComponent = route.component;
                            return (
                                <Route
                                    key={route.key}
                                    path={route.path}
                                    element={
                                        <React.Suspense fallback={null}>
                                            <RouteComponent />
                                        </React.Suspense>
                                    }
                                />
                            );
                        })}

                        <Route path="/" element={<ProjectDetails />}>
                            <Route path="/project/task/list/:id" element={<ProjectDetailsList />} />
                            <Route path="/project/task/board/:id" element={<ProjectDetailsBoard />} />
                            <Route path="/project/task/calendar/:id" element={<ProjectDetailsCalendar />} />
                            <Route path="/project/task/gantt/:id" element={<ProjectDetailsGanttChart />} />
                            <Route path="/project/task/report/:id" element={<ProjectDetailsReport />} />

                            <Route path="/project/task/list/section/by/priority/:id" element={<ProjectDetailsListSectionByPriority />} />
                            <Route path="/project/task/list/section/by/status/:id" element={<ProjectDetailsListSectionByStatus />} />
                            <Route path="/project/task/list/section/by/member/:id" element={<ProjectDetailsListSectionByMember />} />
                            <Route path="/project/task/list/section/by/duedate/:id" element={<ProjectDetailsListSectionByDueDate />} />

                            <Route path="/project/task/board/section/by/priority/:id" element={<ProjectDetailsBoardSectionByPriority />} />
                            <Route path="/project/task/board/section/by/status/:id" element={<ProjectDetailsBoardSectionByStatus />} />
                            <Route path="/project/task/board/section/by/member/:id" element={<ProjectDetailsBoardSectionByMember />} />
                            <Route path="/project/task/board/section/by/duedate/:id" element={<ProjectDetailsBoardSectionByDueDate />} />
                            {whiteboardRoutes.length > 0 && whiteboardRoutes.map((white_route, index) => (
                                white_route.key === 'whiteboard' && (
                                    <Route
                                        key={white_route.key + index}
                                        path={white_route.path}
                                        element={
                                            <WhiteboardRoute
                                                routeKey={white_route.key}
                                                component={white_route.component}
                                                {...white_route.meta}
                                            />
                                        }
                                    />
                                )
                            ))}
                            {!whiteboardRoutes.some(r => r.key === 'whiteboard') && whiteboardAddonState === 'installed_active' && (
                                <Route path="/project/whiteboard/:id" element={<WhiteboardOutdatedFallback />} />
                            )}
                        </Route>

                    </Route>
                    <Route path="/" element={<ProtectedWithoutHeader signedIn={signedIn} />}>
                        {whiteboardRoutes.length > 0 && whiteboardRoutes.map((white_route, index) => (
                            white_route.key === 'whiteboard-fullscreen' && (
                                <Route
                                    key={white_route.key + index}
                                    path={white_route.path}
                                    element={
                                        <WhiteboardRoute
                                            routeKey={white_route.key}
                                            component={white_route.component}
                                            {...white_route.meta}
                                        />
                                    }
                                />
                            )
                        ))}
                    </Route>
                    <Route path="/" element={<PublicRoute authenticated={signedIn} />}>
                        <Route path="/" element={<Login />} />
                        <Route path="/lazy-login" element={<Login />} />
                        <Route path="/forget-password" element={<ForgetPassword />} />
                        <Route path="/change-password" element={<ChangePassword />} />
                    </Route>

                    {/*<Route path="/project/project-details" element={<ProjectDetails />} />*/}
                    {/*<Route path="/project/project-board" element={<ProjectDetails />} />*/}

                    {/* Fallback route for unmatched paths */}
                    <Route path="*" element={<NotFound />} />
                </Routes>
            </HashRouter>

            {/* Global EditTaskDrawer — rendered at the app root so it works on any page,
                including addon routes like /time-tracker that don't render ProjectDetails */}
            <Drawer
                opened={taskEditDrawerOpen}
                onClose={handlerCloseTaskEditDrawer}
                position="right"
                withCloseButton={false}
                size="lg"
                closeOnClickOutside={true}
                overlayProps={{ backgroundOpacity: 0.3, blur: 1 }}
                lockScroll={true}
            >
                <React.Suspense fallback={null}>
                    <EditTaskDrawer
                        lockScroll={true}
                        taskObj={editTask}
                        taskId={editTask && editTask.id}
                        taskEditDrawerOpen={taskEditDrawerOpen}
                    />
                </React.Suspense>
            </Drawer>
        </>
    );
};

// Exposes the HashRouter's navigate function to addon bundles that can't share the router context.
function NavigateBridge() {
    const navigate = useNavigate();
    useEffect(() => { window.__lazytasksNavigate = navigate; }, [navigate]);
    return null;
}

function ProtectedWithHeader({ element, signedIn }) {
    return (
        <>
            <Header />
            <ProtectedRoute element={element} authenticated={signedIn} />
        </>
    );
}
function ProtectedWithoutHeader({ element, signedIn }) {
    return (
        <ProtectedRoute element={element} authenticated={signedIn} />
    );
}

export default AppRoutes;
