import { useState, useCallback } from 'react';
import { clsx } from 'clsx';
import { ChevronUp } from '@transferwise/icons';
import IconButton from '../../../iconButton';
import { useIntl } from 'react-intl';
import messages from './Expander.messages';

export type ExpanderState = {
  expanded: boolean;
  toggle: () => void;
  setExpanded: (expanded: boolean) => void;
};

// Hook for managing expander state
export function useExpanderState(initialExpanded = true): ExpanderState {
  const [expanded, setExpanded] = useState(initialExpanded);

  const toggle = useCallback(() => {
    setExpanded((prev) => !prev);
  }, []);

  return {
    expanded,
    toggle,
    setExpanded,
  };
}

// Helper for conditional rendering based on expanded state
export function shouldShowWhenExpanded({
  expanded,
  hasContent,
  alwaysShow = false,
}: {
  expanded: boolean;
  hasContent: boolean;
  alwaysShow?: boolean;
}): boolean {
  if (alwaysShow) {
    return hasContent;
  }

  return expanded && hasContent;
}

export type ExpanderToggleProps = {
  expanded: boolean;
  onToggle?: () => void;
  size?: 16 | 24 | 32 | 40 | 48 | 56 | 72;
  className?: string;
  'data-testid'?: string;
};

// Reusable toggle button component
export const ExpanderToggle = ({
  expanded,
  onToggle,
  size = 24,
  className,
  'data-testid': testId,
}: ExpanderToggleProps) => {
  const intl = useIntl();

  return (
    <IconButton
      size={size}
      priority="secondary"
      aria-label={intl.formatMessage(
        expanded ? messages.collapseAriaLabel : messages.expandAriaLabel,
      )}
      aria-expanded={expanded}
      className={clsx(
        'wds-expander-toggle',
        { 'wds-expander-toggle--collapsed': !expanded },
        className,
      )}
      data-testid={testId}
      onClick={onToggle}
    >
      <ChevronUp />
    </IconButton>
  );
};
