import React from "react";

type StateArgs = {done?:boolean, open?:boolean};
type StateObj = {done:boolean, open:boolean};
type StateBinding = [state:StateObj, update:(args:StateArgs)=>void];

const CTX = React.createContext([{done:true, open:false}, (args)=>{}] as StateBinding);

export const Group =(props:{children:React.JSX.Element|React.JSX.Element[]})=>
{
    const [stateGet, stateSet] = React.useState({done:true, open:false} as StateObj);
    return <CTX.Provider value={[stateGet, (args:StateArgs)=> stateSet({...stateGet, ...args})]}>{props.children}</CTX.Provider>;
};

export const Menu =(props:{children:React.JSX.Element|React.JSX.Element[]})=>
{
    const [stateGet, stateSet] = React.useContext(CTX);
    const refElement:React.MutableRefObject<HTMLElement|null> = React.useRef( null );
    const refControl:React.MutableRefObject<CollapseControls|null> = React.useRef( null );

    const classDefault = "relative transition-all duration-700 border";
    const classOpen = "h-auto w-auto top-10 px-4 ";
    const classShut = "h-0 w-[300px] top-0 px-0";

    window.TwindInst(classDefault);
    window.TwindInst(classOpen);
    window.TwindInst(classShut);

    React.useEffect(()=>refControl.current = Collapser(refElement.current as HTMLElement, true), []);
    React.useEffect(()=> {refControl.current && refControl.current(stateGet.open, 1000, ()=>stateSet({done:true}))}, [stateGet.open])

    return <div class={classDefault} data-class={classDefault} data-class-open={classOpen} data-class-shut={classShut} ref={refElement as React.Ref<HTMLDivElement>}>{props.children}</div>;
};

export const Button =()=>
{
    const [stateGet, stateSet] = React.useContext(CTX);
    return <>
        <p>{JSON.stringify(stateGet)}</p>
        <button class="px-10 py-2 bg-red-500 text-white" onClick={e=>stateSet({open:true,  done:false})}>Open</button>
        <button class="px-10 py-2 bg-red-500 text-white" onClick={e=>stateSet({open:false, done:false})}>Close</button>
    </>;
};

type DoneCallback =(openState:boolean)=>void;
export type CollapseControls =(inOpen?:boolean, inMs?:number, inDone?:DoneCallback)=>void;
export function Collapser(inElement:HTMLElement, initialState = false)
{
    let userDone:DoneCallback = (openState) => {};
    let userMode = initialState;
    let frameRequest = 0;

    const done = (inEvent:TransitionEvent)=>
    {
      if (inEvent.propertyName == "height" && inEvent.target == inElement)
      {
        inEvent.stopPropagation();
        if (userMode)
        {
          inElement.style.height = "auto";
          inElement.style.overflow = "visible";
        }
        userDone(userMode);
      }
    };
    inElement.addEventListener("transitionend", done);

    return function(inOpen, inMs, inDone)
    {
      cancelAnimationFrame(frameRequest);

      if(arguments.length)
      {
        userDone = inDone|| ((m)=>{}) as DoneCallback;
        userMode = inOpen === true;

        // 1) capture current state and possible classes
        const h1 = inElement.clientHeight;
        const w1 = inElement.clientWidth;
        const classesInitial = inElement.getAttribute("class");
        const classesStart = inElement.getAttribute("data-class");
        const classesEnd = inElement.getAttribute(`data-class-${inOpen?"open":"shut"}`);
      
        // 2) disable transitions to get immediate results
        inElement.style.transition = "none";
        inElement.style.height = "";
        inElement.style.width = "";

        // 3) add new classes and capture new height
        inElement.className = classesStart + " " + classesEnd;
        const h2 = inElement.clientHeight;
        const w2 = inElement.clientWidth;

        // 4) put everything back (and turn on overflow hidden)
        inElement.style.height = h1+"px";
        inElement.style.width = w1+"px";
        inElement.style.overflow = "hidden";
        inElement.className = classesInitial;

        console.log(`BEFORE classes:"${inElement.className}" width:"${w1}" height:"${h1}"`);

        frameRequest = requestAnimationFrame(()=>
        {
          inElement.style.transition = "";
          frameRequest = requestAnimationFrame(()=>
          {
              inElement.style.height = `${h2}px`;
              inElement.style.width = `${w2}px`;
              inElement.className = classesStart + " " + classesEnd;
              console.log(`AFTER classes:"${inElement.className}" width:"${w2}" height:"${h2}"`);
          });
          
        });
      }
      else
      {
        inElement.removeEventListener("transitionend", done);
      }
    } as CollapseControls;
}