import type { ComponentProps } from 'react';
import { cx } from 'class-variance-authority';
import * as CollapsiblePrimitives from '@radix-ui/react-collapsible';
import type { CollapsibleTriggerProps } from '@radix-ui/react-collapsible';

import { Icon } from '../iconography';
import './collapsible.css';

type CollapsibleContentProps = ComponentProps<typeof CollapsiblePrimitives.Content>;

function Content({ className, ...delegated }: CollapsibleContentProps) {
  return <CollapsiblePrimitives.Content {...delegated} className={cx('c-collapsible-content', className)} />;
}

type CollapsibleTriggerPropsExtendedProps = CollapsibleTriggerProps & {
  arrowPosition?: 'left' | 'right';
  mode?: 'tree';
};

export function CollapsibleTrigger({
  children,
  arrowPosition,
  className,
  mode,
  ...delegated
}: CollapsibleTriggerPropsExtendedProps) {
  return (
    <CollapsiblePrimitives.Trigger
      asChild
      {...delegated}
      className={cx(
        'c-collapsible-trigger',
        arrowPosition === 'right' ? 'arrow-right' : '',
        mode === 'tree' ? 'c-collapsible-tree' : '',
        className,
      )}
    >
      <div>
        {arrowPosition && <Icon.Caret className="c-collapsible-arrow" width={9} height={9} />}
        {children}
      </div>
    </CollapsiblePrimitives.Trigger>
  );
}

export const Collapsible = {
  Root: CollapsiblePrimitives.Root,
  Trigger: CollapsibleTrigger,
  Content,
};
