import { useCallback, useState } from "react";

import type { FC, PropsWithChildren, ReactNode } from "react";
import "../style/controls/sameSectionAccordion.scss";

const SameSectionAccordion: FC<
    PropsWithChildren<{
        title: string | ReactNode;
        onToggle?: (state: boolean) => void;
        state?: boolean;
        grouped?: boolean;
    }>
> = ({ title, children, onToggle, state, grouped }) => {
    // Uncontrolled
    const [open, setOpen] = useState(false);
    const handleClick = useCallback(() => {
        onToggle?.(!open);
        setOpen(!open);
    }, [open, setOpen]);

    // Controlled
    const useOpen = state === undefined ? open : state;

    return (
        <li
            className={`accordion-section same-section-accordion ${useOpen ? "same-section-accordion-open" : ""}`}
            style={{ marginBottom: grouped ? 0 : undefined, borderBottom: grouped ? 0 : undefined }}
        >
            <div className="accordion-section-title" onClick={handleClick}>
                <strong>{title}</strong>
            </div>
            {useOpen && <div>{children}</div>}
        </li>
    );
};

export { SameSectionAccordion };
