import React from 'react';
import { GlyphIcon } from '@theorchard/suite-icons';
import cx from 'classnames';
import { Expandable } from '../expandable';
import { t } from './i18n';
import type { ComponentBaseWithChildrenProps } from '../../types';

export const CLASSNAME = 'ExpandableContent';
export const LABEL_CLASSNAME = `${CLASSNAME}-label`;
export const LABEL_WRAPPER_CLASSNAME = `${LABEL_CLASSNAME}-wrapper`;
export const CONTENT_CLASSNAME = `${CLASSNAME}-content`;

export interface ExpandableContentProps extends ComponentBaseWithChildrenProps {
    style?: React.CSSProperties;
    expandLabel?: React.ReactNode;
    collapseLabel?: React.ReactNode;
    /**
     * Default expanded state of the content.
     */
    defaultExpanded?: boolean;
    /**
     * Controlled property for the expanded state of the content.
     */
    expanded?: boolean;
    /**
     * Callback function triggered when the expanded state changes.
     */
    onToggle?(isExpanded: boolean): void;
    /**
     * @deprecated Use onToggle instead
     */
    onClick?(isExpanded: boolean): void;
}

/**
 * ExpandableContent displays content that can be toggled between expanded and collapsed states inside a container (e.g. Section).
 *
 * @type organism
 * @status live
 * @tags utilities
 */
export const ExpandableContent: React.FC<ExpandableContentProps> = ({
    children,
    expandLabel = t('more_info'),
    collapseLabel,
    className,
    style,
    defaultExpanded = false,
    expanded,
    testId = CLASSNAME,
    onToggle,
    onClick,
}) => {
    const resolvedCollapseLabel = collapseLabel || expandLabel; // Fallback logic

    const onToggleHandler = onToggle || onClick;

    return (
        <Expandable
            defaultExpanded={defaultExpanded}
            expanded={expanded}
            onExpanded={onToggleHandler}
        >
            <div className={cx(CLASSNAME, className)} style={style} data-testid={testId}>
                <Expandable.Trigger as="div" className={LABEL_WRAPPER_CLASSNAME}>
                    {(isExpanded) => (
                        <>
                            <span className={LABEL_CLASSNAME}>
                                {isExpanded ? resolvedCollapseLabel : expandLabel}
                            </span>
                            <GlyphIcon
                                name={isExpanded ? 'doubleChevronUp' : 'doubleChevronDown'}
                                size={12}
                            />
                        </>
                    )}
                </Expandable.Trigger>
                <Expandable.Body className={CONTENT_CLASSNAME}>{children}</Expandable.Body>
            </div>
        </Expandable>
    );
};
