import React, {useEffect, useRef, useState} from "react";
import "./SidebarComponents.scss";
import CloseButton from "../CloseButton/CloseButton";
import PageTitle from "../Typography/PageTitle";
import {renderTemplate} from "../Templates/RenderTemplate";

// --- SHARED STATE ---
let globalOpenKey: string | null = null;
let listeners: ((key: string | null) => void)[] = [];

const setGlobalOpenKey = (key: string | null) => {
    globalOpenKey = key;

    const floatingWidgets = document.querySelector(
        '#floating-widgets-container, .floating-widgets-container'
    ) as HTMLElement | null;
    if (floatingWidgets) {
        floatingWidgets.style.display = key ? 'none' : 'block';
    }

    listeners.forEach(l => l(key));
};

// SidebarComponents.tsx — make sure this is exported
export const subscribeToOpenKey = (set: (key: string | null) => void) => {
    listeners.push(set);
    return () => {
        listeners = listeners.filter(l => l !== set);
    };
};

// Closes whichever sidebar overlay is currently open, and resets the
// z-index bump applied to the header/profile while it was open.
// Use this to programmatically close the active overlay from outside
// (e.g. after a successful form submission inside its children).
export const closeActiveSidebarOverlay = () => {
    const header = document.querySelector('.service-header') as HTMLElement | null;
    const profile = document.querySelector('.profile') as HTMLElement | null;
    if (header) header.style.zIndex = '100';
    if (profile) profile.style.zIndex = '1000';
    setGlobalOpenKey(null);
};

const dataCache: Record<string, any> = {};

// --- Sidebar Overlay ---
type SidebarOverlayProps = {
    isOpen: boolean;
    data: any;
    onClose: () => void;
    title:React.ReactNode;
    person?:React.ReactNode;
    templateName?:string |null |undefined;
    children: any,
    icon?: string;

};




const SidebarOverlay: React.FC<SidebarOverlayProps> = ({ isOpen, data, onClose,title,person, icon, children }) => {
    useEffect(() => {
        const header = document.querySelector('.service-header') as HTMLElement | null;
        const profile = document.querySelector('.profile') as HTMLElement | null;

        const handleClickOutside = (e: MouseEvent) => {
            const sidebar = document.querySelector('.sidebar-overlay');

            // If sidebar exists and the click target is outside it
            if (isOpen && sidebar && !sidebar.contains(e.target as Node)) {
                if (header) header.style.zIndex = '100';
                if (profile) profile.style.zIndex = '1000';
                onClose();
            }
        };

        const handleEscape = (e: KeyboardEvent) => {
            if (e.key === "Escape") {
                if (header) header.style.zIndex = '100';
                if (profile) profile.style.zIndex = '1000';
                onClose();
            }
        };

        if (isOpen) {
            document.addEventListener("mousedown", handleClickOutside);
            document.addEventListener("keydown", handleEscape);
        }

        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
            document.removeEventListener("keydown", handleEscape);
        };
    }, [isOpen, onClose]);
    // This useEffect ensures zIndex is reset on unmount
    useEffect(() => {
        return () => {
            const header = document.querySelector('.service-header') as HTMLElement | null;
            const profile = document.querySelector('.profile') as HTMLElement | null;

            if (header) header.style.zIndex = '100';
            if (profile) profile.style.zIndex = '1000';
        };
    }, []);


    return isOpen ? (
        <div className={`sidebar-backdrop ${isOpen ? 'open' : ''}`} onClick={onClose}>
            <div
                className={`sidebar-overlay ${isOpen ? 'open' : 'closed'}`}
                onClick={(e) => e.stopPropagation()}
            ><div className={'sidebar-header'}>
                <CloseButton onClick={onClose}/>

            </div>
                <div className="sidebar-content">
                    {/* <div>
                        {renderTemplate({ data, templateName })}
                    </div> */}
                    {children}
                </div>
            </div>
        </div>
    ) : null;
};

// --- Sidebar Button with Overlay ---
type SidebarButtonProps = {
    label?: any;
    customClass?: string;
    dataKey?: string;
    fetchData?: () => Promise<any>;
    data?: any;
    icon?: any;
    rowKey?:any;
    title:React.ReactNode;
    person?:React.ReactNode;
    templateName?:string |null | undefined;
    children?: any;
    buttonProp?:React.ReactNode;
};

export const SidebarButtonWithOverlay: React.FC<SidebarButtonProps> = ({buttonProp, rowKey,
                                                                           children,
                                                                           label,
                                                                           dataKey,
                                                                           fetchData,
                                                                           data,
                                                                           icon,
                                                                           person,
                                                                           title,

                                                                       }) => {
    const uniqueKey = `${dataKey}:${rowKey}`;
    const [isOpen, setIsOpen] = useState(false);
    const [sidebarData, setSidebarData] = useState<any>(null);
    const header = document.querySelector('.service-header') as HTMLElement;
    const profile = document.querySelector('.profile') as HTMLElement;
    useEffect(() => {
        return subscribeToOpenKey((key) => {
            const opening = key === uniqueKey;
            setIsOpen(opening);
            if (opening && dataCache[uniqueKey]) {
                setSidebarData(dataCache[uniqueKey]);
            } else if (!opening) {
                setSidebarData(null);
            }
        });
    }, [uniqueKey]);

    const handleClick = async () => {

        if (header) {
            header.style.zIndex = '4';
        }
        if (profile) {
            profile.style.zIndex = '4';
        }
        if (isOpen) {
            setGlobalOpenKey(null);
            if (header) {
                header.style.zIndex = '100';
            }
            if (profile) {
                profile.style.zIndex = '1000';
            }
            return;
        }

        if (dataCache[uniqueKey]) {
            setSidebarData(dataCache[uniqueKey]);
            setGlobalOpenKey(uniqueKey);
            return;
        }

        let result = data;
        if (fetchData) {
            try {
                result = await fetchData();
            } catch (err) {
                result = { error: "Failed to load data" };
            }
        }

        dataCache[uniqueKey] = result;
        setSidebarData(result);
        setGlobalOpenKey(uniqueKey);
    };

    return (
        <><div onClick={handleClick}>
            {buttonProp}
        </div>

            <button onClick={handleClick} className="sidebar-button d-flex align-items-center justify-content-center flex-column">
                {typeof icon === 'string' ? (
                    <img style={{width:'20px'}} src={icon} alt="icon" className="sidebar-icon" />
                ) : (
                    icon && <span className="sidebar-icon">{icon}</span>
                )}
                {/* {icon && <img src={icon} alt="icon" className="sidebar-icon" />} */}
                {label}
            </button>
            <SidebarOverlay title={title} icon={icon} person={person} isOpen={isOpen} data={sidebarData} onClose={() => { if (header) {
                header.style.zIndex = '100';
            }
                if (profile) {
                    profile.style.zIndex = '1000';
                }setGlobalOpenKey(null)} }>
                <div id={'childrens'}>
                    {typeof children === 'function' ? children(isOpen) : children}
                </div>

            </SidebarOverlay>

        </>
    );
};
