import React, { useState, useEffect } from 'react';
import { getImagePath } from '../../lib/utils';

export function SharedHeader({ 
    title = "Overview", 
    showDateRangePicker = false,
    dateRangeValue = null,
    onDateRangeChange = null,
    showBackButton = false,
    onBackClick = null,
    className = ""
}) {
    const [showUserMenu, setShowUserMenu] = useState(false);

    // Handle clicks outside user menu to close it
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showUserMenu && !event.target.closest('.user-menu-container')) {
                setShowUserMenu(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showUserMenu]);

    const handleLogout = () => {
        localStorage.removeItem('accessToken');
        window.location.href = '/login';
    };

    return (
        <header className={`bg-white border-b border-gray-200 px-6 md:px-4 sm:px-3 py-4 md:py-3 sm:py-2 fixed top-0 right-0 left-48 md:left-48 sm:left-16 z-10 dashboard-header ${className}`}>
            <div className="flex items-center justify-between">
                {/* Overview Heading and Back Button */}
                <div className="overview-section flex items-center space-x-4">
                    {showBackButton && onBackClick && (
                        <button 
                            onClick={onBackClick}
                            className="p-2 md:p-2 sm:p-1.5 hover:bg-gray-100 rounded-md transition-colors"
                        >
                            <img src={getImagePath("left-arrow-icon.svg")} alt="Back" className="w-2 h-2 md:w-2 md:h-2 sm:w-1.5 sm:h-1.5" />
                        </button>
                    )}
                    <h2 className="text-lg md:text-base sm:text-sm font-semibold text-gray-600 overview-title">{title}</h2>
                </div>
                
                {/* Date Range Picker and User Menu */}
                <div className="flex items-center space-x-4 md:space-x-3 sm:space-x-2 right-section">
                    {showDateRangePicker && onDateRangeChange && (
                        <div className="date-range-section md:block sm:hidden">
                            <input
                                type="date"
                                value={dateRangeValue?.from ? format(dateRangeValue.from, 'yyyy-MM-dd') : ''}
                                onChange={(e) => {
                                    if (e.target.value) {
                                        const newDate = new Date(e.target.value);
                                        onDateRangeChange({ from: newDate, to: dateRangeValue?.to || newDate });
                                    }
                                }}
                                className="w-40 md:w-32 sm:w-28 h-10 md:h-9 sm:h-8 px-3 md:px-2 sm:px-2 py-2 border border-gray-300 rounded-md text-sm"
                            />
                        </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-40 sm:w-36 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-3 sm:px-2 py-2 md:py-1.5 sm:py-1 text-sm md:text-sm sm:text-xs text-gray-700 hover:bg-gray-100 transition-colors flex items-center gap-2"
                                    >
                                        <svg className="w-4 h-4 md:w-3.5 md:h-3.5 sm:w-3 sm:h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-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>
            </div>
        </header>
    );
}

// Helper function for date formatting
function format(date, formatString) {
    if (!date) return '';
    
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    
    return formatString
        .replace('yyyy', year)
        .replace('MM', month)
        .replace('dd', day);
}
