import { useCallback } from "react";
import { OSExpanderProps } from "./props";
import { OSLabel, OSLabelProps } from "../label";
import React from "react";
import { Collapse } from "../collapse";
import { useExposableState } from "../../hooks";

/**
 * Divider component to seperate/hide sections of the user interface.
 */
export function OSExpander({
    children,
    open,
    setOpen,
    header,
    label,
    ...props
}: OSExpanderProps) {
    //Current state of divider
    const [isOpen, setIsOpen] = useExposableState(false, open, setOpen);

    /** Toggle state internally */
    const onToggle = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        setIsOpen(x => !x)
        e.preventDefault();
    }, [isOpen]);

    return (<>
        <div {...props} className={["os-divider", "flex", "flex-col", "w-full", props.className].join(" ")} data-os-divider-open={isOpen} >
            {/** Header */}
            {header !== false && <div className={`os-divider-header grid gap-2${children ? " os-clickable" : ""}`} 
                onClick={onToggle} 
                style={{gridTemplateColumns: `auto ${label ? 'auto' : ''} 1fr`}}>
                {/** Use <i> instead of OSIcon until transition animations are solved */}
                {children ? <i className={`os-icon fa-fw fa-chevron-right fa-classic os-divider-chevron self-center`} data-os-divider-open={isOpen} />
                    : (label && <div className="os-divider-hr border-t-1 fa-fw self-center" />)}
                {label && (React.isValidElement(label)
                    ? label
                    : <OSLabel {...(label as OSLabelProps)}
                        style={{ ...(label as OSLabelProps).style}}
                        className={["os-divider-label", "select-none", (label as OSLabelProps).className ?? ""].join(" ")}
                        inline
                        />)}
                <div className="flex w-full place-items-center">{header}</div>
            </div>}

            {/** Content */}
            <Collapse className="os-divider-content" collapsed={!isOpen} children={children}/>
        </div>
    </>)
};