import { useEffect } from "react";
interface ScrollLinkProps {
    targetId: string;
    label: string;
}
const ScrollLink: React.FC<ScrollLinkProps> = ({ targetId, label }) => {
    const handleClick = (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
        event.preventDefault(); // Prevent default anchor behavior
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
            const elementRect = targetElement.getBoundingClientRect();
            const elementTop = elementRect.top + window.scrollY;
            const viewportHeight = window.innerHeight;
            const scrollOffset = elementTop - (viewportHeight / 2 - targetElement.offsetHeight / 2);
            
            console.log(`Element Top: ${elementTop}`);
            console.log(`Viewport Height: ${viewportHeight}`);
            console.log(`Scroll Offset: ${scrollOffset}`);
            
            window.scrollTo({
                top: scrollOffset,
                behavior: "smooth"
            });
        } else {
            console.error(`Element with ID ${targetId} not found.`);
        }
    };

    return (
        <a href={`#${targetId}`} onClick={handleClick}>
            {label}
        </a>
    );
};


export function SafetySidebar(){
    let nums = [ "del1"]
    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
      }, []);
      const handleScroll = () => {
          for(let idx in nums){
            /* console.log("We are looking at 'item' = " + nums[idx]) */
              const item = nums[idx];
              let ind = nums.findIndex((e) => e == item)
             /*  console.log("ind is: " + ind) */
              let subdi = "subtitle" + ind 
              /* console.log("subdi is: " + subdi)
              console.log("we use " +  document.getElementById(item)?.id + " and " + document.getElementById(subdi)?.id) */
              Highlight({el: document.getElementById(item)!}, {subtitle: document.getElementById(subdi)!});
          }       
          /*     */
      }
      /* console.log(nums) */


    return(
        <div className="col-2 d-none d-lg-block">
            <br/>
            <div className="sticky-top">
            <nav className="sidebar">
            <div> 
                <a onClick={openAndCloseAndScroll({ it: "tab-Role", scrollTarget: "Role" })}>
                    <div className="detail-sideitem">
                        <div id="parent-Role" className="sideitem">
                            <summary>Role in iGem</summary>
                        </div>
                    </div>
                </a>
            </div>
            <div> 
                <a onClick={openAndCloseAndScroll({ it: "tab-Checks", scrollTarget: "Checks" })}>
                    <div className="detail-sideitem">
                        <div id="parent-Checks" className="sideitem">
                            <summary>Check-Ins</summary>
                        </div>
                    </div>
                </a>
            </div>
            <div> 
                <a onClick={openAndCloseAndScroll({ it: "tab-Lab", scrollTarget: "Lab" })}>
                    <div className="detail-sideitem">
                        <div id="parent-Lab" className="sideitem">
                            <summary>Our Lab</summary>
                        </div>
                    </div>
                </a>
            </div>            
                <div> 
                    {/* Fznktioniert:  <a onClick={openThem({it: "tab-Cystic-Fibrosis"})}  > */}
                        <div className="detail-sideitem">
                            <div id="parent-Biosafety" className="sideitem">
                              <a onClick={openAndScroll({ it: "tab-Biosafety", scrollTarget: "Biosafety" })}><summary>Biosafety</summary></a> 
                                <span id="tab-Biosafety" className="sidesubtab" style={{display: "none"}}>
                                     <ul>
                                        <li><ScrollLink label="Mechanism" targetId="BS1"/></li>
                                        <li><ScrollLink label="Delivery" targetId="BS2"/></li>
                                    </ul>
                                </span>
                            </div> 
                        </div>
                </div> 
                <div> 
                    {/* Fznktioniert:  <a onClick={openThem({it: "tab-Cystic-Fibrosis"})}  > */}
                        <div className="detail-sideitem">
                            <div id="parent-Biosecurity" className="sideitem">
                              <a onClick={openAndScroll({ it: "tab-Biosecurity", scrollTarget: "Biosecurity" })}><summary>Biosecurity</summary></a> 
                                <span id="tab-Biosecurity" className="sidesubtab" style={{display: "none"}}>
                                     <ul>
                                        <li><ScrollLink label="Our Project" targetId="BSec1"/></li>
                                        <li><ScrollLink label="Risk Assesment" targetId="BSec2"/></li>
                                        <li><ScrollLink label="Managing Risks" targetId="BSec3"/></li>
                                    </ul>
                                </span>
                            </div> 
                        </div>
                </div> 
                <div> 
                        <div className="detail-sideitem">
                            <div id="parent-Bioethics" className="sideitem">
                              <a onClick={openAndScroll({ it: "tab-Bioethics", scrollTarget: "Bioethics" })}><summary>Bioethics</summary></a> 
                                <span id="tab-Bioethics" className="sidesubtab" style={{display: "none"}}>
                                     <ul>
                                        <li><ScrollLink label="Gene Therapy" targetId="BE1"/></li>
                                        <li><ScrollLink label="Primary Cells" targetId="BE2"/></li>
                                        <li><ScrollLink label="Consent and Guidelines" targetId="BE3"/></li>
                                    </ul>
                                </span>
                            </div> 
                        </div>
                </div> 
            </nav>   
        <br/>
        <div className="col" style={{display: "flex", alignItems: "right"}}>
            <a href='#' className="backtotop">
                Back to Top &#8593;
            </a>
        </div>  
            </div>
        </div>
        
    )
}


function Highlight({el}: {el: HTMLElement | null}, {subtitle}:{subtitle: HTMLElement | null}){
    let TopDistance = 150; 
  /*   console.log("Starting highlight check...")
    console.log("here come el...")
    console.log(el)
    console.log("here comes subtitle...")
    console.log(subtitle) */
    if (el != null && subtitle != null){
/*         console.log("here comes el...")
        console.log(el)
        console.log(el.getBoundingClientRect()) */
        if (el.getBoundingClientRect().top < TopDistance + 1 && el.getBoundingClientRect().bottom > TopDistance){
            subtitle.style.color = "blue";
            subtitle.style.backgroundColor = "rgb(133, 15, 120, 0.8)";
            subtitle.style.borderColor = "#850F78"; 
            subtitle.style.marginLeft = "10px"; 
            subtitle.style.paddingRight = "10px"; 

/*                 console.log("subtitle: ",subtitle)
            console.log("style: ", subtitle.style)
            console.log("color: ",subtitle.style.color)
            console.log("backcolor: ",subtitle.style.backgroundColor)    */     
        }
        else{
            subtitle.style.color = "white";
            subtitle.style.marginLeft = "0"; 
            subtitle.style.backgroundColor = "";
        }
    }
    
  }

   

 function openAndScroll({ it, scrollTarget }: { it: string, scrollTarget?: string }) {
    const gotoandopen = (_event: React.MouseEvent<HTMLElement, MouseEvent>) => {
        _event.preventDefault(); // Prevent default anchor behavior

        console.log(`openAndScroll called with it: ${it} and scrollTarget: ${scrollTarget}`);

        // Attempt to find the elements
        const subtabElement = document.getElementById(it);
        const parentElementId = "parent-" + it.replace("tab-", "");
        const parentElement = document.getElementById(parentElementId);

        console.log(`subtabElement with ID ${it}: `, subtabElement);
        console.log(`parentElement with ID ${parentElementId}: `, parentElement);
        if (scrollTarget === "Biosafety"){
            document.getElementById("tab-Biosecurity")!.style.display = "none"; 
            document.getElementById("parent-Biosecurity")!.classList.remove("active-sideitem");
           
            document.getElementById("tab-Bioethics")!.style.display = "none"; 
            document.getElementById("parent-Bioethics")!.classList.remove("active-sideitem");
        }
        if (scrollTarget === "Biosecurity"){
            document.getElementById("tab-Biosafety")!.style.display = "none"; 
            document.getElementById("parent-Biosafety")!.classList.remove("active-sideitem");
           
            document.getElementById("tab-Bioethics")!.style.display = "none"; 
            document.getElementById("parent-Bioethics")!.classList.remove("active-sideitem");
        }
        if (scrollTarget === "Bioethics"){
            document.getElementById("tab-Biosecurity")!.style.display = "none"; 
            document.getElementById("parent-Biosecurity")!.classList.remove("active-sideitem");
           
            document.getElementById("tab-Biosafety")!.style.display = "none"; 
            document.getElementById("parent-Biosafety")!.classList.remove("active-sideitem");
        }
        if (subtabElement && parentElement) {
            console.log("Found subtabElement and parentElement.");
            // Show the selected tab in the sidebar and add active class
            subtabElement.style.display = "block";
            parentElement.classList.add("active-sideitem");
        } else {
            console.error(`Subtab element or parent element not found for ID: ${it}`);
        }

        // If a scroll target is provided, scroll to that element on the page
        if (scrollTarget) {
            const targetElement = document.getElementById(scrollTarget);
            if (targetElement) {
                console.log(`Scrolling to element with ID: ${scrollTarget}`);
                
                // Get the position of the element relative to the document
                const elementRect = targetElement.getBoundingClientRect();
                const elementTop = elementRect.top + window.scrollY;
                
                // Calculate the middle of the viewport
                const viewportHeight = window.innerHeight;
                const scrollOffset = elementTop - (viewportHeight / 2 - targetElement.offsetHeight / 2);
               /*  
                console.log(`Element Top: ${elementTop}`);
                console.log(`Viewport Height: ${viewportHeight}`);
                console.log(`Scroll Offset: ${scrollOffset}`); */
                
                window.scrollTo({
                    top: scrollOffset,
                    behavior: "smooth"
                });
            } else {
                console.error(`Scroll target element not found for ID: ${scrollTarget}`);
            }
        }
    }
    return gotoandopen;
}

 function openAndCloseAndScroll({ it, scrollTarget }: { it: string, scrollTarget?: string }) {
    const gotoandopen = (_event: React.MouseEvent<HTMLElement, MouseEvent>) => {
        _event.preventDefault(); // Prevent default anchor behavior

        console.log(`openAndScroll called with it: ${it} and scrollTarget: ${scrollTarget}`);

        // Attempt to find the elements
        const subtabElement = document.getElementById(it);
        const parentElementId = "parent-" + it.replace("tab-", "");
        const parentElement = document.getElementById(parentElementId);


            document.getElementById("tab-Biosafety")!.style.display = "none"; 
            document.getElementById("parent-Biosafety")!.classList.remove("active-sideitem");
           
            document.getElementById("tab-Biosecurity")!.style.display = "none"; 
            document.getElementById("parent-Biosecurity")!.classList.remove("active-sideitem");
           
            document.getElementById("tab-Bioethics")!.style.display = "none"; 
            document.getElementById("parent-Bioethics")!.classList.remove("active-sideitem");
           
        
 
        
        console.log(`subtabElement with ID ${it}: `, subtabElement);
        console.log(`parentElement with ID ${parentElementId}: `, parentElement);

        if (subtabElement && parentElement) {
            console.log("Found subtabElement and parentElement.");
            // Show the selected tab in the sidebar and add active class
            subtabElement.style.display = "block";
            parentElement.classList.add("active-sideitem");
        } else {
            console.error(`Subtab element or parent element not found for ID: ${it}`);
        }

        // If a scroll target is provided, scroll to that element on the page
        if (scrollTarget) {
            const targetElement = document.getElementById(scrollTarget);
            if (targetElement) {
                console.log(`Scrolling to element with ID: ${scrollTarget}`);
                
                // Get the position of the element relative to the document
                const elementRect = targetElement.getBoundingClientRect();
                const elementTop = elementRect.top + window.scrollY;
                
                // Calculate the middle of the viewport
                const viewportHeight = window.innerHeight;
                const scrollOffset = elementTop - (viewportHeight / 2 - targetElement.offsetHeight / 2);
               /*  
                console.log(`Element Top: ${elementTop}`);
                console.log(`Viewport Height: ${viewportHeight}`);
                console.log(`Scroll Offset: ${scrollOffset}`); */
                
                window.scrollTo({
                    top: scrollOffset,
                    behavior: "smooth"
                });
            } else {
                console.error(`Scroll target element not found for ID: ${scrollTarget}`);
            }
        }
    }
    return gotoandopen;
}