import React, { useMemo, useState } from 'react';
import { LayoutAnimation, View } from 'react-native';
import { useTheme } from '../../branding';
import Pill from '../Pill';
import styles from './styles.ts';
import type { ExpandableListProps } from './types.ts';

const configureListAnimation = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
};

export const ExpandableList = ({
    children,
    maxVisible,
    style
}: ExpandableListProps) => {
    const { theme } = useTheme();
    const themedStyles = styles[theme];
    const [isExpanded, setIsExpanded] = useState(false);

    const childElements = useMemo(
        () => React.Children.toArray(children).filter(React.isValidElement),
        [children]
    );

    const hasOverflow = childElements.length > maxVisible;
    const isFullyVisible = isExpanded || !hasOverflow;
    const visibleChildren = isFullyVisible
        ? childElements
        : childElements.slice(0, maxVisible);

    const handleExpandPress = () => {
        configureListAnimation();
        setIsExpanded(true);
    };

    const handleCollapsePress = () => {
        configureListAnimation();
        setIsExpanded(false);
    };

    return (
        <View style={[themedStyles.container, style]} testID="expandable-list">
            {visibleChildren}
            {hasOverflow && !isExpanded ? (
                <Pill
                    doubleChevron
                    onPress={handleExpandPress}
                    testID="expandable-list-expand-pill"
                />
            ) : null}
            {hasOverflow && isExpanded ? (
                <Pill
                    doubleChevronUp
                    onPress={handleCollapsePress}
                    testID="expandable-list-collapse-pill"
                />
            ) : null}
        </View>
    );
};

export default ExpandableList;
