import clsx from "clsx";
import { Collapsible as CollapsiblePrimitive } from "radix-ui";
import * as React from "react";
import { useEvent, useGetKey, useGetSet } from "../../hooks";
import { ButtonContext } from "../Link";
import * as styles from "./styles.module.css";

export const Collapsible = ({
  defaultOpen = false,
  children,
  preview,
  onOpenChange,
  ...rest
}: CollapsiblePrimitive.CollapsibleProps & {
  preview?: true;
  "data-id": string;
}) => {
  const key = useGetKey(rest);
  const [{ isOpen }, setState] = useGetSet(key, { isOpen: defaultOpen }, true);
  const open = React.useCallback(() => {
    setState({ isOpen: true }, process.env.PREVIEW ? `onChange` : undefined);
  }, [setState]);
  const close = React.useCallback(() => {
    setState({ isOpen: false }, process.env.PREVIEW ? `onChange` : undefined);
  }, [setState]);
  const id = rest["data-id"];
  useEvent(id, "open", open);
  useEvent(id, "close", close);
  return (
    <CollapsiblePrimitive.Root
      open={preview || isOpen}
      onOpenChange={(isOpen) => {
        setState({ isOpen }, process.env.PREVIEW ? `onChange` : undefined);
        onOpenChange?.(isOpen);
      }}
      data-component="Collapsible$Brevity"
      {...rest}
    >
      {children}
    </CollapsiblePrimitive.Root>
  );
};

Collapsible.Trigger = (props: CollapsiblePrimitive.CollapsibleTriggerProps) => {
  return (
    <ButtonContext value={true}>
      <CollapsiblePrimitive.CollapsibleTrigger {...props} />
    </ButtonContext>
  );
};

Collapsible.Content = ({
  className,
  ...props
}: CollapsiblePrimitive.CollapsibleContentProps) => {
  return (
    <CollapsiblePrimitive.CollapsibleContent
      className={clsx("__collapsible-content", styles.content, className)}
      {...props}
    />
  );
};
