import ReactDOM from 'react-dom';
import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";
import PanelActions from './actions/PanelActions';
import { useEffect, useState } from 'react';
import CouponPanel from './CouponPanel';
import {LegacyModelSelectorButton} from "./tree/LegacyModelSelectorButton";

const {setActivePanel} = PanelActions;

const getHeaderTargetElement = () => $('.cp-after-code')[0]

const HeaderPortal = ({ children }) => {
    const portalRoot = getHeaderTargetElement();

    return ReactDOM.createPortal(children, portalRoot);
};

export const Tabs = ({panels}) => {
    const dispatch = useDispatch()
    const selectedPanel = useSelector(state => state.selectedPanel) || CouponPanel.label
    const [canRender, setCanRender] = useState(false)

    useEffect(() => {
        const interval = setInterval(() => {
            if (getHeaderTargetElement()) {
                clearInterval(interval)
                setCanRender(true)
            }
        }, 500)
    }, [])

    if (!canRender) {
        return null
    }

    const panelButton = Panel => (
        <button
            key={Panel.label}
            className={classNames({
                'relative flex flex-row items-center justify-center h-10 px-3 capitalize rounded-full hover:cursor-pointer hover:bg-blue-tint-500 hover:bg-opacity-10 hover:text-blue-lighter focus:outline-none transition': true,
                'bg-blue-tint-500 bg-opacity-20 text-blue-lighter': selectedPanel === Panel.label
            })}
            onClick={() => dispatch(setActivePanel(Panel.label))}
        >
            <div className="flex flex-row items-center justify-center space-x-2">
                <span>{Panel.getIcon()}</span><span className="flex h-5">{Panel.label}</span>
            </div>
            {selectedPanel === Panel.label && (
                <div className="absolute bottom-[-10px] w-full h-[2px] bg-blue-lighter rounded-t-6 ml-o"></div>
            )}
        </button>
    )
    return <HeaderPortal>
        <div className="text-2x text-gray-600 flex flex-row space-x-2 flex-shrink-0">
            <div className="text-2x flex flex-row space-x-2">
                {panels.filter(Panel => !Panel?.aside).map(Panel => {
                    return panelButton(Panel)
                })}
            </div>
            <div className="text-2x flex flex-row space-x-2 pl-2 border-l-[2px] border-gray-300">
                {panels.filter(Panel => Panel?.aside).map(Panel => {
                    return panelButton(Panel)
                })}
            </div>
        </div>
    </HeaderPortal>
}