import React, { useMemo, useState } from 'react';
import { LayoutAnimation, View } from 'react-native';
import { useTheme } from '../../../branding';
import Pill from '../../../componentsDS/Pill';
import { getRegionName } from '../../../services/region.service';
import type { RegionName } from '../../../constants/regions';
import { isRegionSelected } from '../utils';
import { regions as quickSelectionRegions } from '../constants';
import themedStyles from './styles';

const REGIONS_PER_ROW = 3;
const VISIBLE_ROWS_COLLAPSED = 1;

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

interface RegionQuickSelectionProps {
    selectedCountryCodes: string[];
    onRegionPress: (region: RegionName) => void;
}

export const RegionQuickSelection = ({
    selectedCountryCodes,
    onRegionPress
}: RegionQuickSelectionProps) => {
    const { theme } = useTheme();
    const styles = themedStyles[theme];
    const [isExpanded, setIsExpanded] = useState(false);

    const visibleRegions = useMemo(() => {
        const regionNames = quickSelectionRegions.map(({ value }) => value);
        const visibleRegionCount = isExpanded
            ? regionNames.length
            : REGIONS_PER_ROW * VISIBLE_ROWS_COLLAPSED;

        return regionNames.slice(0, visibleRegionCount);
    }, [isExpanded]);

    const hasOverflow =
        quickSelectionRegions.length > REGIONS_PER_ROW * VISIBLE_ROWS_COLLAPSED;

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

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

    return (
        <View style={styles.container} testID="region-quick-selection">
            {visibleRegions.map(region => (
                <Pill
                    key={region}
                    label={getRegionName(region).toUpperCase()}
                    selected={isRegionSelected(region, selectedCountryCodes)}
                    onPress={() => onRegionPress(region)}
                    testID={`region-quick-selection-pill-${region}`}
                />
            ))}
            {hasOverflow && !isExpanded ? (
                <Pill
                    doubleChevron
                    onPress={handleExpandPress}
                    testID="region-quick-selection-expand-pill"
                />
            ) : null}
            {hasOverflow && isExpanded ? (
                <Pill
                    doubleChevronUp
                    onPress={handleCollapsePress}
                    testID="region-quick-selection-collapse-pill"
                />
            ) : null}
        </View>
    );
};

export default RegionQuickSelection;
