import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Users } from 'lucide-react';
import { isTokenExpired, logoutUser, getTokenRemainingTime } from '../../lib/api';
import { getImagePath } from '../../lib/utils';

export function Layout({ 
    children, 
    title, 
    currentPage = "dashboard",
    showSidebar = true,
    showHeader = true,
    className = ""
}) {
    const navigate = useNavigate();
    const [showUserMenu, setShowUserMenu] = useState(false);
    const [showExpirationWarning, setShowExpirationWarning] = useState(false);
    const [sidebarOpen, setSidebarOpen] = useState(true);

    // Check token expiration every minute
    useEffect(() => {
        const checkTokenExpiration = () => {
            if (isTokenExpired()) {
                console.log('Token expired, logging out user');
                logoutUser();
            } else {
                // Check if token expires in less than 30 minutes
                const remainingTime = getTokenRemainingTime();
                const thirtyMinutes = 30 * 60 * 1000; // 30 minutes in milliseconds
                
                if (remainingTime < thirtyMinutes && remainingTime > 0) {
                    setShowExpirationWarning(true);
                } else {
                    setShowExpirationWarning(false);
                }
            }
        };

        // Check immediately
        checkTokenExpiration();

        // Check every minute
        const interval = setInterval(checkTokenExpiration, 60000);

        return () => clearInterval(interval);
    }, []);

    const handleLogout = () => {
        logoutUser();
    };

    const handleViolationsClick = () => {
        navigate('/dashboard');
    };

    const handleConstablesClick = () => {
        navigate('/constables');
    };

    return (
        <div className={`flex h-screen bg-gray-50 overflow-hidden ${className}`}>
            {/* Fixed Sidebar */}
            {showSidebar && (
                <div className={`${sidebarOpen ? 'w-48 lg:w-48 md:w-40 sm:w-32 xs:w-24' : 'w-16 lg:w-16 md:w-12 sm:w-10 xs:w-8'} bg-white border-r border-gray-200 flex flex-col fixed left-0 top-20 lg:top-20 md:top-16 sm:top-12 xs:top-10 h-full z-30 transition-all duration-300`}>
                    {/* Sidebar Toggle Button */}
                    <div className="p-2 border-b border-gray-200">
                        <button 
                            onClick={() => setSidebarOpen(!sidebarOpen)}
                            className="w-8 h-8 flex items-center justify-center text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-md transition-colors"
                        >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={sidebarOpen ? "M6 18L18 6M6 6l12 12" : "M4 6h16M4 12h16M4 18h16"} />
                            </svg>
                        </button>
                    </div>

                    <nav className="flex-1 p-4 lg:p-4 md:p-3 sm:p-2 xs:p-1 space-y-2 lg:space-y-2 md:space-y-1.5 sm:space-y-1 xs:space-y-1">
                        {/* Violations - Selected/Unselected based on current page */}
                        <div
                            className={`flex items-center justify-between p-3 md:p-3 sm:p-2 rounded-lg cursor-pointer transition-colors ${
                                currentPage === "dashboard" 
                                    ? "bg-blue-50 hover:bg-blue-100" 
                                    : "bg-gray-50 hover:bg-gray-100"
                            }`}
                            onClick={handleViolationsClick}
                        >
                            <div className="flex items-center space-x-3 lg:space-x-3 md:space-x-2 sm:space-x-1.5 xs:space-x-1">
                                <div className="w-5 h-5 lg:w-5 lg:h-5 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5 xs:w-3 xs:h-3 flex items-center justify-center">
                                    <svg className={`w-5 h-5 lg:w-5 lg:h-5 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5 xs:w-3 xs:h-3 ${
                                        currentPage === "dashboard" ? "text-blue-600" : "text-gray-500"
                                    }`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
                                    </svg>
                                </div>
                                {sidebarOpen && (
                                    <span className={`font-medium text-xs lg:text-xs md:text-sm sm:text-xs xs:text-xs font-sans ${
                                        currentPage === "dashboard" ? "text-blue-700" : "text-gray-600"
                                    }`}>Violations</span>
                                )}
                            </div>
                            {currentPage === "dashboard" && sidebarOpen && (
                                <div className="w-2 h-2 lg:w-2 lg:h-2 md:w-1.5 md:h-1.5 sm:w-1 sm:h-1 xs:w-1 xs:h-1 bg-blue-500 rounded-full"></div>
                            )}
                        </div>

                        {/* Constables - Selected/Unselected based on current page */}
                        <div
                            className={`flex items-center justify-between p-3 md:p-3 sm:p-2 rounded-lg cursor-pointer transition-colors ${
                                currentPage === "constables" 
                                    ? "bg-blue-50 hover:bg-blue-100" 
                                    : "bg-gray-50 hover:bg-gray-100"
                            }`}
                            onClick={handleConstablesClick}
                        >
                            <div className="flex items-center space-x-3 lg:space-x-3 md:space-x-2 sm:space-x-1.5 xs:space-x-1">
                                <div className="w-5 h-5 lg:w-5 lg:h-5 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5 xs:w-3 xs:h-3 flex items-center justify-center">
                                    <svg className={`w-5 h-5 lg:w-5 lg:h-5 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5 xs:w-3 xs:h-3 ${
                                        currentPage === "constables" ? "text-blue-600" : "text-gray-500"
                                    }`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                                    </svg>
                                </div>
                                {sidebarOpen && (
                                    <span className={`font-medium text-xs lg:text-xs md:text-sm sm:text-xs xs:text-xs font-sans ${
                                        currentPage === "constables" ? "text-blue-700" : "text-gray-600"
                                    }`}>Constables</span>
                                )}
                            </div>
                            {currentPage === "constables" && sidebarOpen && (
                                <div className="w-2 h-2 lg:w-2 lg:h-2 md:w-1.5 md:h-1.5 sm:w-1 sm:h-1 xs:w-1 xs:h-1 bg-blue-500 rounded-full"></div>
                            )}
                        </div>
                    </nav>
                </div>
            )}

            {/* Main Content Area */}
            <div className={`flex-1 flex flex-col ${showSidebar ? (sidebarOpen ? 'ml-48 lg:ml-48 md:ml-40 sm:ml-32 xs:ml-24' : 'ml-16 lg:ml-16 md:ml-12 sm:ml-10 xs:ml-8') : 'ml-0'} mt-4 lg:mt-4 md:mt-3 sm:mt-2 xs:mt-1 transition-all duration-300`}>
                {/* Fixed Header */}
                {showHeader && (
                    <header className="bg-white border-b border-gray-200 px-6 lg:px-6 md:px-4 sm:px-3 xs:px-2 py-2 lg:py-2 md:py-1.5 sm:py-1 xs:py-1 fixed top-0 left-0 right-0 z-20">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-6 lg:space-x-6 md:space-x-4 sm:space-x-3 xs:space-x-2">
                                {/* Logo and Divider */}
                                <div className="flex items-center">
                                    <img src={getImagePath("pushpakAI-logo.svg")} alt="PUSHPAK.AI" className="h-14 w-[145px] lg:h-14 lg:w-[145px] md:h-12 md:w-[120px] sm:h-10 sm:w-[100px] xs:h-8 xs:w-[80px]" />
                                </div>
                                <div className="border-l border-gray-300 h-12 lg:h-12 md:h-10 sm:h-8 xs:h-6"></div>
                                <div className="flex items-center space-x-4 lg:space-x-4 md:space-x-3 sm:space-x-2 xs:space-x-1">
                                    {title && <h1 className="text-lg lg:text-lg md:text-base sm:text-sm xs:text-xs font-bold text-gray-900 font-sans">{title}</h1>}
                                </div>
                            </div>
                            <div className="relative user-menu-container">
                                <button
                                    onClick={() => setShowUserMenu(!showUserMenu)}
                                    className="w-12 h-12 lg:w-11 lg:h-11 md:w-10 md:h-10 sm:w-9 sm:h-9 xs:w-8 xs:h-8 rounded-full flex items-center justify-center hover:bg-gray-100 transition-colors cursor-pointer border-2 border-gray-200 hover:border-gray-300"
                                >
                                    <img src={getImagePath("user-circle-icon.svg")} alt="User" className="w-10 h-10 lg:w-9 lg:h-9 md:w-8 md:h-8 sm:w-7 sm:h-7 xs:w-6 xs:h-6" />
                                </button>

                                {/* User Dropdown Menu */}
                                {showUserMenu && (
                                    <div className="absolute right-0 mt-2 w-48 md:w-48 sm:w-40 bg-white rounded-md shadow-lg border border-gray-200 z-20">
                                        <div className="py-1">
                                            <button
                                                onClick={handleLogout}
                                                className="w-full text-left px-4 md:px-4 sm:px-3 py-2 md:py-2 sm:py-1.5 text-xs md:text-sm sm:text-xs text-gray-700 hover:bg-gray-100 transition-colors flex items-center gap-2 font-sans"
                                            >
                                                <svg className="w-4 h-4 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                                                </svg>
                                                Logout
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </header>
                )}

                {/* Token Expiration Warning */}
                {showExpirationWarning && (
                    <div className="fixed top-20 right-4 z-50 bg-yellow-100 border border-yellow-400 text-yellow-800 px-4 py-3 rounded-lg shadow-lg">
                        <div className="flex items-center space-x-2">
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                            </svg>
                            <span className="font-medium">
                                Your session will expire in less than 30 minutes. Please save your work.
                            </span>
                            <button 
                                onClick={() => setShowExpirationWarning(false)}
                                className="ml-2 hover:bg-yellow-200 rounded-full p-1"
                            >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                    </div>
                )}

                {/* Scrollable Content */}
                <div className={`flex-1 p-6 md:p-6 sm:p-4 space-y-6 md:space-y-6 sm:space-y-4 ${showHeader ? 'mt-16 md:mt-16 sm:mt-12' : ''} overflow-y-auto bg-white`}>
                    {children}
                </div>

                {/* Footer */}
                <div className="bg-white px-4 md:px-4 sm:px-3 py-2 md:py-2 sm:py-1.5 text-left text-xs md:text-sm sm:text-xs text-gray-400">
                    <p>© 2025 PushpakAI. All rights reserved.</p>
                </div>
            </div>
        </div>
    );
}
