import { useState, useEffect, useCallback } from 'react';
import { Clock, RefreshCw } from 'lucide-react';
import { useAuth } from '../../context/AuthContext';

const SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour
const WARNING_THRESHOLD = 5 * 60 * 1000; // 5 minutes before expiry
const CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds

export function SessionTimeoutWarning() {
    const { logout } = useAuth();
    const [showWarning, setShowWarning] = useState(false);
    const [timeRemaining, setTimeRemaining] = useState(0);

    const getTokenExpiry = useCallback(() => {
        const token = localStorage.getItem('token');
        if (!token) return null;

        try {
            // Decode JWT to get expiry
            const payload = JSON.parse(atob(token.split('.')[1]));
            return payload.exp ? payload.exp * 1000 : null; // Convert to ms
        } catch {
            return null;
        }
    }, []);

    const refreshSession = useCallback(async () => {
        try {
            const refreshToken = localStorage.getItem('refreshToken');
            if (refreshToken) {
                const response = await fetch(`${import.meta.env.VITE_API_URL || '/api'}/auth/refresh`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ refreshToken })
                });

                if (response.ok) {
                    const data = await response.json();
                    localStorage.setItem('token', data.accessToken);
                    if (data.refreshToken) {
                        localStorage.setItem('refreshToken', data.refreshToken);
                    }
                    setShowWarning(false);
                    return true;
                }
            }
        } catch (e) {
            console.error('Failed to refresh session:', e);
        }
        return false;
    }, []);

    useEffect(() => {
        const checkSession = () => {
            const expiry = getTokenExpiry();
            if (!expiry) return;

            const now = Date.now();
            const remaining = expiry - now;

            if (remaining <= 0) {
                // Session expired
                logout();
            } else if (remaining <= WARNING_THRESHOLD) {
                // Show warning
                setShowWarning(true);
                setTimeRemaining(Math.ceil(remaining / 1000));
            } else {
                setShowWarning(false);
            }
        };

        // Initial check
        checkSession();

        // Periodic check
        const interval = setInterval(checkSession, CHECK_INTERVAL);

        // Also update countdown every second when warning is shown
        const countdownInterval = setInterval(() => {
            if (showWarning) {
                setTimeRemaining(prev => Math.max(0, prev - 1));
            }
        }, 1000);

        return () => {
            clearInterval(interval);
            clearInterval(countdownInterval);
        };
    }, [getTokenExpiry, logout, showWarning]);

    if (!showWarning) return null;

    const minutes = Math.floor(timeRemaining / 60);
    const seconds = timeRemaining % 60;

    return (
        <div className="fixed bottom-24 md:bottom-8 left-4 z-[100] max-w-sm">
            <div className="bg-amber-50 dark:bg-amber-900/50 border border-amber-200 dark:border-amber-700 rounded-xl p-4 shadow-lg animate-slide-in">
                <div className="flex items-start gap-3">
                    <div className="p-2 bg-amber-100 dark:bg-amber-800 rounded-full">
                        <Clock size={20} className="text-amber-600 dark:text-amber-400" />
                    </div>
                    <div className="flex-1">
                        <h4 className="font-bold text-amber-800 dark:text-amber-200">Session Expiring</h4>
                        <p className="text-sm text-amber-700 dark:text-amber-300 mt-1">
                            Your session will expire in{' '}
                            <span className="font-mono font-bold">
                                {minutes}:{seconds.toString().padStart(2, '0')}
                            </span>
                        </p>
                        <div className="flex gap-2 mt-3">
                            <button
                                onClick={refreshSession}
                                className="flex items-center gap-1 px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white text-sm font-medium rounded-lg transition-colors"
                            >
                                <RefreshCw size={14} />
                                Stay Logged In
                            </button>
                            <button
                                onClick={logout}
                                className="px-3 py-1.5 text-amber-700 dark:text-amber-300 text-sm font-medium hover:underline"
                            >
                                Log Out
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
