import { Message, Video } from '@/types/ask';
import { MaterialItem } from '@/types/personal-info';
import React, { Dispatch, ForwardedRef, forwardRef, memo, SetStateAction, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
    FlatList,
    FlatListProps,
    SafeAreaView,
    View
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import MessageItem from './aiChat';

// 继承 FlatListProps 来接收所有 FlatList 的属性
interface ChatProps extends Omit<FlatListProps<Message>, 'data' | 'renderItem'> {
    userMessages: Message[];
    sessionId: string;
    setSelectedImages: Dispatch<SetStateAction<string[]>>;
    selectedImages: string[];
}

function ChatComponent(
    { userMessages, sessionId, setSelectedImages, selectedImages, ...restProps }: ChatProps,
    ref: ForwardedRef<FlatList<Message>>
) {
    const insets = useSafeAreaInsets();
    const [modalVisible, setModalVisible] = React.useState({ visible: false, data: {} as Video | MaterialItem });
    const { t } = useTranslation();
    const keyExtractor = useCallback((item: Message) => `${item.role}-${item.timestamp}`, []);

    const contentContainerStyle = useMemo(() => ({
        padding: 16,
        flexGrow: 1,
        paddingTop: 0,
    }), []);

    const [modalDetailsVisible, setModalDetailsVisible] = useState<{ visible: boolean, content: any }>({ visible: false, content: [] });

    return (
        <SafeAreaView style={{ flex: 1 }}>
            <FlatList
                ref={ref}
                data={userMessages}
                keyExtractor={keyExtractor}
                renderItem={({ item, index }) => {
                    const itemStyle = index === 0 ? { marginTop: 16, marginHorizontal: 16 } : { marginHorizontal: 16 };
                    return (
                        <View style={itemStyle}>
                            {MessageItem({ t, setSelectedImages, selectedImages, insets, item, sessionId, modalVisible, setModalVisible, setModalDetailsVisible, modalDetailsVisible })}
                        </View>
                    );
                }}
                contentContainerStyle={contentContainerStyle}
                keyboardDismissMode="interactive"
                keyboardShouldPersistTaps="handled"
                removeClippedSubviews={true}
                maxToRenderPerBatch={10}
                updateCellsBatchingPeriod={50}
                initialNumToRender={10}
                windowSize={11}
                {...restProps} // 将所有其他属性传递给 FlatList
            />
        </SafeAreaView>
    );
}

export default memo(forwardRef(ChatComponent));