"use strict";
"use client";

import React, { createContext, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';

interface User {
    id: number;
    email: string;
    username: string;
    name: string;
    role: 'user' | 'admin';
    created_at: string;
    two_factor_enabled?: boolean;
    email_verified?: boolean;
    newsletter_subscribed?: boolean;
    personnummer?: string;
    mobile?: string;
    address?: string;
    zip_code?: string;
    city?: string;
    country?: string;
    has_password?: boolean;
}

interface AuthContextType {
    user: User | null;
    loading: boolean;
    login: (token: string, user: User, rememberMe?: boolean) => void;
    logout: () => void;
    isAuthenticated: boolean;
    refreshUser: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType>({
    user: null,
    loading: true,
    login: () => { },
    logout: () => { },
    isAuthenticated: false,
    refreshUser: () => Promise.resolve(),
});

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);
    const router = useRouter();

    const logout = React.useCallback(() => {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('user');
        setUser(null);
        router.push('/login');
    }, [router]);

    const refreshUser = async () => {
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        if (!token) return;

        try {
            const res = await fetch('/api/auth/me', {
                headers: { 'Authorization': `Bearer ${token}` }
            });

            if (res.ok) {
                const data = await res.json();
                setUser(data.user);

                const storage = localStorage.getItem('token') ? localStorage : sessionStorage;
                storage.setItem('user', JSON.stringify(data.user));
            } else {
                // Token invalid/expired - clear session if refresh fails
                logout();
            }
        } catch (error) {
            console.error("Manual refresh failed", error);
        }
    };

    useEffect(() => {
        const initAuth = async () => {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const storedUser = localStorage.getItem('user') || sessionStorage.getItem('user');

            // 1. Instant re-hydration from storage
            if (storedUser) {
                try {
                    setUser(JSON.parse(storedUser));
                    setLoading(false); // Stop showing "Laddar" immediately if we have a cached user
                } catch (e) {
                    console.error("Failed to parse stored user", e);
                }
            }

            // 2. Background validation
            if (token) {
                await refreshUser();
            }

            setLoading(false);
        };

        initAuth();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 3. Security: Idle Timer (Auto-logout after 15 minutes of inactivity)
    useEffect(() => {
        if (!user) return;

        const IDLE_TIMEOUT = 15 * 60 * 1000; // 15 minutes
        let idleTimer: NodeJS.Timeout;

        const resetTimer = () => {
            if (idleTimer) clearTimeout(idleTimer);
            idleTimer = setTimeout(() => {
                console.log("[Auth] User idle for 15 minutes. Logging out for security.");
                logout();
            }, IDLE_TIMEOUT);
        };

        // Events that indicate user is active
        const activityEvents = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click'];

        activityEvents.forEach(event => {
            window.addEventListener(event, resetTimer);
        });

        resetTimer(); // Start the timer

        return () => {
            if (idleTimer) clearTimeout(idleTimer);
            activityEvents.forEach(event => {
                window.removeEventListener(event, resetTimer);
            });
        };
    }, [user, logout]);

    const login = (token: string, userData: User, rememberMe?: boolean) => {
        // If rememberMe is not provided, detect if we're already using localStorage
        const usingLocal = rememberMe !== undefined ? rememberMe : !!localStorage.getItem('token');

        if (usingLocal) {
            localStorage.setItem('token', token);
            localStorage.setItem('user', JSON.stringify(userData));
            sessionStorage.removeItem('token');
            sessionStorage.removeItem('user');
        } else {
            sessionStorage.setItem('token', token);
            sessionStorage.setItem('user', JSON.stringify(userData));
            localStorage.removeItem('token');
            localStorage.removeItem('user');
        }
        setUser(userData);
    };


    return (
        <AuthContext.Provider value={{ user, loading, login, logout, isAuthenticated: !!user, refreshUser }}>
            {children}
        </AuthContext.Provider>
    );
};

export const useAuth = () => useContext(AuthContext);
