import {Accordion} from "react-bootstrap";
import React, {ReactElement, useState, useEffect} from "react";

export interface Item {
    header: string, // Unique item header. 
    visible: boolean,
    expanded: boolean,
}

interface AccordionGroupProps {
    itemData: { [itemHeader: string]: Item }, 
    itemRenderer: (val: Item) => ReactElement,
    toggleAll: boolean,
}
export const AccordionGroup = ({itemData, itemRenderer, toggleAll}: AccordionGroupProps) => 
{   
    // Determine which accordion items should be expanded:
    let mainExpandKeys = new Set<string>(Object.values(itemData)
        .map((item: Item) => item.expanded ? item.header : null)
        .filter(itemKey => itemKey !== null));
    
    const [expanded, setExpanded] = useState<Set<string>>(mainExpandKeys);
    
    useEffect(() => {
        if (toggleAll === null) {
            setExpanded(new Set([...mainExpandKeys, ...expanded]));
        } else {
            setExpanded(new Set(toggleAll ? Object.keys(itemData) : []));
        }
    }, [itemData, toggleAll]); 

    let items: ReactElement[] = Object.values(itemData).map(itemRenderer);
    
    return <Accordion activeKey={[...expanded]} onSelect={keyArr => setExpanded(new Set(keyArr))} alwaysOpen>{items}</Accordion>
}
export interface AccordionGroupItemProps extends Item {
    expanded?: boolean, // Optional, as this is largely controlled by parent Accordion.
    title: string, // Friendly ALT title.
    onClick?: ()=>void
    children: string|ReactElement,
}
export const AccordionGroupItem = ({header, title, visible, children, onClick}: AccordionGroupItemProps) => {
    return <Accordion.Item eventKey={header} key={header} className={visible ? '' : 'd-none'} >
        <Accordion.Header title={title} className="white-space-pre-wrap" onClick={onClick}>{header}</Accordion.Header>
        <Accordion.Body>
            {children}
        </Accordion.Body>
    </Accordion.Item>
}