// @flow
import React, { useCallback, useState } from 'react';
import type { ExpanderContextType, ExpanderProps } from './expander.proptypes';
import { UnstyledButton } from '../unstyled-button';

export const ExpanderContext: React$Context<ExpanderContextType> = React.createContext(
  { toggleExpander: () => {} },
);

export const Expander = ({
  children,
  headingComponent,
  headingComponentOpen,
  isOpen = false,
  onToggle,
  buttonStyles,
  'data-qa': dataQa,
  'data-cy': dataCy,
  id,
}: ExpanderProps) => {
  const [open, setOpen] = useState(isOpen);

  const handleToggle = useCallback(() => {
    const toggledState = !open;
    setOpen(toggledState);

    if (typeof onToggle === 'function') {
      onToggle(toggledState);
    }
  }, [open, setOpen, onToggle]);

  return (
    <ExpanderContext.Provider value={{ toggleExpander: handleToggle }}>
      <UnstyledButton
        style={buttonStyles}
        onClick={handleToggle}
        data-cy={dataCy}
        data-qa={dataQa}
        id={id}
      >
        {open && headingComponentOpen ? headingComponentOpen : headingComponent}
      </UnstyledButton>
      {open ? children : null}
    </ExpanderContext.Provider>
  );
};

Expander.displayName = 'Expander';
