import { createSignal, FlowComponent, JSX, mergeProps } from "solid-js";
import Collapsible from "./Collapsible";

const createAccordion = (defaultItem: number | null = 0) => {
  const [item, setItem] = createSignal(defaultItem);
  const AccordionItem: FlowComponent<{
    label?: JSX.Element;
    item?: number;
    activeTitleColor?: string;
  }> = (p) => {
    const props = mergeProps({ item: Math.random() }, p);

    return (
      <Collapsible
        class="border-b-0 last:border-b first:rounded-t last:rounded-b"
        value={item() === props.item}
        label={
          <div class="flex justify-center items-center gap-2">
            {props.label}
          </div>
        }
        activeTitleColor={props.activeTitleColor}
        onChange={(evt: any) =>
          setItem(evt.currentTarget.checked && props.item)
        }
      >
        {props.children}
      </Collapsible>
    );
  };

  return [AccordionItem, item, setItem] as [
    typeof AccordionItem,
    typeof item,
    typeof setItem
  ];
};

export default createAccordion;
