import React, { useContext } from 'react';
import { Accordion } from '@digigov/react-core/Accordion';
import {
  AccordionSection,
  type AccordionSectionProps,
} from '@digigov/react-core/AccordionSection';
import { Button, ButtonProps } from '@digigov/react-core/Button';
import {
  AccordionItemId,
  useAccordion,
  UseAccordionReturn,
} from '@digigov/ui/content/Accordion/hooks';

export interface ButtonAccordionAutoProps extends ButtonProps {}
export interface AccordionSectionAutoProps extends AccordionSectionProps {
  id: string;
}

const AccordionContext = React.createContext<UseAccordionReturn | null>(null);
export const AccordionAuto = ({
  singleOpen,
  defaultOpen,
  children,
  ...props
}: {
  singleOpen?: boolean;
  defaultOpen?: AccordionItemId;
  children: React.ReactNode;
}) => {
  const accordion = useAccordion({
    singleOpen,
    defaultOpen,
  });

  return (
    <AccordionContext.Provider value={accordion}>
      <Accordion {...props}>{children}</Accordion>
    </AccordionContext.Provider>
  );
};
export const useAccordionContext = (): UseAccordionReturn | null => {
  const context = useContext(AccordionContext);
  if (context === null) {
    throw new Error(
      'AccordionContext must be used within an AccordionProvider'
    );
  }
  return context;
};

export const AccordionSectionAuto = React.forwardRef<
  HTMLDetailsElement,
  AccordionSectionAutoProps
>(function AccordionSectionAuto({ id, ...props }, ref) {
  const context = useAccordionContext();
  if (!context) {
    throw new Error(
      'AccordionSectionAuto must be used within an AccordionProvider'
    );
  }
  const { section } = context;
  return (
    <AccordionSection
      {...section(id)}
      ref={section(id).ref || ref}
      {...props}
    />
  );
});

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

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