import React, { useContext } from 'react';
import { Button, ButtonProps } from '@digigov/react-core/Button';
import StepNav from '@digigov/react-core/StepNav';
import {
  StepNavAccordion,
  StepNavAccordionProps,
} from '@digigov/react-core/StepNavAccordion';
import {
  UseAccordionReturn as useStepNavReturn,
  AccordionItemId as StepNavItemId,
  useAccordion as useStepNav,
} from '@digigov/ui/content/Accordion/hooks';

export interface ButtonAutoProps extends ButtonProps {}
export interface StepNavAccordionAutoProps extends StepNavAccordionProps {
  id: string;
}

const StepNavContext = React.createContext<useStepNavReturn | null>(null);
export const StepNavAuto = ({
  singleOpen,
  defaultOpen,
  children,
  ...props
}: {
  singleOpen?: boolean;
  defaultOpen?: StepNavItemId;
  children: React.ReactNode;
}) => {
  const accordion = useStepNav({
    singleOpen,
    defaultOpen,
  });

  return (
    <StepNavContext.Provider value={accordion}>
      <StepNav {...props}>{children}</StepNav>
    </StepNavContext.Provider>
  );
};
export const useStepNavContext = (): useStepNavReturn | null => {
  const context = useContext(StepNavContext);
  return context;
};

export const StepNavAccordionAuto = React.forwardRef<
  HTMLDetailsElement,
  StepNavAccordionAutoProps
>(function StepNavAccordionAuto({ id, ...props }, ref) {
  const context = useStepNavContext();
  if (!context) {
    throw new Error(
      'StepNavAccordionAuto must be used within an StepNavProvider'
    );
  }
  const { section } = context;
  return (
    <StepNavAccordion
      {...section(id)}
      ref={section(id).ref || ref}
      {...props}
    />
  );
});

export const StepNavOpenAllButtonAuto = React.forwardRef<
  HTMLButtonElement,
  ButtonAutoProps
>(function StepNavOpenAllButtonAuto(props, ref) {
  const context = useStepNavContext();
  if (!context) {
    throw new Error(
      'StepNavOpenAllButton must be used within an StepNavProvider'
    );
  }
  const { openAll, hasOpen } = context;
  return !hasOpen ? (
    <Button variant="link" ref={ref} onClick={openAll} {...props} />
  ) : null;
});

export const StepNavCloseAllButtonAuto = React.forwardRef<
  HTMLButtonElement,
  ButtonAutoProps
>(function StepNavCloseAllButtonAuto(props, ref) {
  const context = useStepNavContext();
  if (!context) {
    throw new Error(
      'StepNavCloseAllButton must be used within an StepNavProvider'
    );
  }
  const { closeAll, hasOpen } = context;
  return hasOpen ? (
    <Button variant="link" ref={ref} onClick={closeAll} {...props} />
  ) : null;
});
