import { ReactNode, useState, useEffect, useRef } from 'react';
import { usePage } from '@inertiajs/react';
import Header from '../Header/Header';
import Notification from '../Notification/Notification';
import UserSidebar from '../Sidebar/UserSidebar';

interface UserLayoutProps {
    children: ReactNode;
    title?: string;
}

export default function UserLayout({ children, title }: UserLayoutProps) {
    const [notification, setNotification] = useState<{ type: 'success' | 'error' | 'warning' | 'info'; message: string } | null>(null);
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
        if (typeof window !== 'undefined') {
            const saved = localStorage.getItem('sidebarCollapsed');
            return saved === 'true';
        }
        return false;
    });
    const { props } = usePage();
    const flash = (props as any).flash || {};
    const lastProcessedFlashRef = useRef<string>('');

    // Handle flash messages
    useEffect(() => {
        let flashType: 'success' | 'error' | 'warning' | 'info' | null = null;
        let flashMessage = '';

        if (flash.success) {
            flashType = 'success';
            flashMessage = flash.success;
        } else if (flash.error) {
            flashType = 'error';
            flashMessage = flash.error;
        } else if (flash.warning) {
            flashType = 'warning';
            flashMessage = flash.warning;
        } else if (flash.info) {
            flashType = 'info';
            flashMessage = flash.info;
        }

        const currentFlashKey = flashType && flashMessage 
            ? `${flashType}-${flashMessage}-${Date.now()}` 
            : '';
        
        if (flashType && flashMessage && currentFlashKey !== lastProcessedFlashRef.current) {
            lastProcessedFlashRef.current = currentFlashKey;
            setNotification(null);
            setTimeout(() => {
                setNotification({ type: flashType!, message: flashMessage });
            }, 100);
        } else if (!flashType && !flashMessage) {
            setNotification(null);
        }
    }, [flash.success, flash.error, flash.warning, flash.info]);

    const handleNotificationClose = () => {
        setNotification(null);
        lastProcessedFlashRef.current = '';
    };

    const handleMenuClick = () => {
        setSidebarOpen(!sidebarOpen);
    };

    const handleSidebarClose = () => {
        setSidebarOpen(false);
    };

    const handleToggleCollapse = () => {
        const newCollapsed = !sidebarCollapsed;
        setSidebarCollapsed(newCollapsed);
        if (typeof window !== 'undefined') {
            localStorage.setItem('sidebarCollapsed', String(newCollapsed));
        }
    };

    return (
        <div className="flex min-h-screen flex-col bg-gray-50 dark:bg-gray-900">
            {/* Sidebar */}
            <UserSidebar 
                isOpen={sidebarOpen} 
                onClose={handleSidebarClose}
                collapsed={sidebarCollapsed}
                onToggleCollapse={handleToggleCollapse}
            />

            {/* Overlay for mobile sidebar */}
            {sidebarOpen && (
                <div
                    className="fixed inset-0 z-40 bg-gray-600 bg-opacity-75 transition-opacity lg:hidden"
                    onClick={handleSidebarClose}
                />
            )}

            {/* Main Content Area */}
            <div className={`transition-all duration-300 ease-in-out ${sidebarCollapsed ? 'lg:pl-20' : 'lg:pl-72'}`}>
                {/* Header */}
                <Header onMenuClick={handleMenuClick} title={title} />

                {/* Main Content */}
                <main className="flex-1">
                    <div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
                        {children}
                    </div>
                </main>
            </div>

            {/* Notification */}
            {notification && (
                <Notification
                    type={notification.type}
                    message={notification.message}
                    onClose={handleNotificationClose}
                />
            )}
        </div>
    );
}


