import React, { useState } from 'react';
import { FlatList, Pressable, Text, View } from 'react-native';
import { useTheme } from '../../branding';
import Close from '../Icons/Close';
import type { ComponentIndexTOCProps, TOCEntry } from './types';
import themedStyles from './styles';

const PANEL_HEADER_TITLE = 'Components';

const ComponentIndexTOC = ({
    entries,
    onSelect,
    testID = 'component-index-toc'
}: ComponentIndexTOCProps) => {
    const [expanded, setExpanded] = useState(false);
    const { theme, colors } = useTheme();
    const styles = themedStyles[theme];

    const handleRowPress = (id: string) => {
        setExpanded(false);
        onSelect(id);
    };

    const renderRow = ({ item }: { item: TOCEntry }) => (
        <Pressable
            style={({ pressed }) => [styles.row, pressed && styles.rowPressed]}
            onPress={() => handleRowPress(item.id)}
            accessibilityLabel={item.name}
            accessibilityRole="button"
        >
            <Text style={styles.rowText}>{item.name}</Text>
        </Pressable>
    );

    if (expanded) {
        return (
            <>
                <Pressable
                    style={styles.backdrop}
                    onPress={() => setExpanded(false)}
                    accessibilityLabel="Close component index"
                    accessibilityRole="button"
                    testID={`${testID}-backdrop`}
                />
                <View style={styles.panel} testID={`${testID}-panel`}>
                    <View style={styles.panelHeader}>
                        <Text style={styles.panelTitle}>
                            {PANEL_HEADER_TITLE}
                        </Text>
                        <Pressable
                            style={styles.closeButton}
                            onPress={() => setExpanded(false)}
                            accessibilityLabel="Close component index"
                            accessibilityRole="button"
                            testID={`${testID}-close`}
                        >
                            <Close color={colors.gray0} size={16} />
                        </Pressable>
                    </View>
                    <FlatList
                        style={styles.list}
                        data={entries}
                        keyExtractor={item => item.id}
                        renderItem={renderRow}
                    />
                </View>
            </>
        );
    }

    return (
        <Pressable
            style={({ pressed }) => [styles.fab, pressed && styles.fabPressed]}
            onPress={() => setExpanded(true)}
            accessibilityLabel="Open component index"
            accessibilityRole="button"
            testID={testID}
        >
            <Text style={styles.fabLabel}>☰</Text>
        </Pressable>
    );
};

export default ComponentIndexTOC;
