'use client';

import { useAppSelector } from "@/redux/store"
import { isLoggedIn, mountCheckIfValid, logOut } from "@/redux/features/auth-slice";
import { useDispatch } from "react-redux"
import { AppDispatch } from '@/redux/store';
import { useEffect, useCallback } from "react";
import { useRouter } from 'next/navigation'
import { ReactNode } from 'react' 
import FullScreenLoader from "@/components/common/fullScreenLoader";
import { load } from '@/redux/features/settings-slice'
import ErrorBoundary from '@/components/common/ErrorBoundary';
import axios from 'axios'; // Added axios import

// HOC for auth pages (only accept auth user)
export default function LocaleLayout({ children }: { children: ReactNode }) {
    const router = useRouter();
    const dispatch = useDispatch<AppDispatch>();
    
    // Load states
    const isValid = useAppSelector((state) => state.authReducer.value.isValid);
    const checkIfValidMounted = useAppSelector((state) => state.authReducer.value.checkIfValidMounted);
    const notAuthRedirectPage = useAppSelector((state) => state.settingsReducer.value.notAuthRedirectPage);
    const isLoadingSettings = useAppSelector((state) => state.settingsReducer.value.isLoadingSettings);
    const loadedFirstTime = useAppSelector((state) => state.settingsReducer.value.loadedFirstTime);

    // Handle not logged in state
    const handleNotLoggedIn = useCallback(() => {
        // Clear any invalid token from cookies
        document.cookie = 'authToken=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        // Clear Redux state
        dispatch(logOut());
        // Redirect to login page
        router.push(notAuthRedirectPage);
    }, [notAuthRedirectPage, router, dispatch]);

    // Initialize auth check
    useEffect(() => {
        if (checkIfValidMounted) return;
        
        const checkAuth = async () => {
            try {
                await dispatch(mountCheckIfValid());
                await dispatch(isLoggedIn({ NotLoggedInCallback: handleNotLoggedIn }));
            } catch (error) {
                console.error('Auth check failed:', error);
                handleNotLoggedIn();
            }
        };

        checkAuth();
    }, [checkIfValidMounted, dispatch, handleNotLoggedIn]);

    // Load settings
    useEffect(() => {
        if (loadedFirstTime || isLoadingSettings) return;
        
        const loadSettings = async () => {
            try {
                await dispatch(load({ page: 1 }));
            } catch (error) {
                console.error('Failed to load settings:', error);
            }
        };

        loadSettings();
    }, [loadedFirstTime, isLoadingSettings, dispatch]);

    // Add global error handler for API requests
    useEffect(() => {
        const responseInterceptor = (response: any) => response;
        
        const errorInterceptor = (error: any) => {
            if (error.response?.status === 401) {
                // Handle unauthorized (token expired/invalid)
                handleNotLoggedIn();
            }
            return Promise.reject(error);
        };
        
        // Add request interceptor
        const requestInterceptor = axios.interceptors.request.use(
            config => config,
            error => Promise.reject(error)
        );
        
        // Add response interceptor
        const responseIntercept = axios.interceptors.response.use(
            responseInterceptor,
            errorInterceptor
        );
        
        // Cleanup function
        return () => {
            axios.interceptors.request.eject(requestInterceptor);
            axios.interceptors.response.eject(responseIntercept);
        };
    }, [handleNotLoggedIn]);

    // Show loading state while checking auth
    if (isValid === null) {
        return <FullScreenLoader />;
    }

    return (
        <ErrorBoundary>
            {isValid ? children : <FullScreenLoader />}
        </ErrorBoundary>
    );
}
