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

/**
 * Divider component to seperate/hide sections of the user interface.
 */
export function OSDivider({
    children,
    label,
    open,
    setOpen,
    ...props
}: OSDividerProps) {
    //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]);

    /* Convert string ReactNodes to OSLabel props for standardized display */
    if (typeof label === "string") {
        label = { label: label }
    };

    return (<>
        <div {...props} className={["os-divider", "flex", "flex-col", "w-full", props.className].join(" ")} data-os-divider-open={isOpen} >
            {/** Header */}
            <div className={`os-divider-header inline-flex gap-2${children ? " os-clickable" : ""}`} onClick={onToggle}>
                {/** Use <i> instead of OSIcon until transition animations are solved */}
                {children ? <Chevron className="os-divider-chevron" toggled={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, gridArea: "label" }}
                        className={["os-divider-label", "select-none", (label as OSLabelProps).className ?? ""].join(" ")}
                        inline />)}
                <div className="os-divider-hr border-t-1 self-center flex-1" />
                {props.actions && <div className="flex place-items-center" onClick={e => e.stopPropagation()}>{props.actions}</div>}
                {props.actions && <div className="os-divider-hr border-t-1 fa-fw self-center" />}
            </div>

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