import ChatSvg from "@/assets/icons/svg/chat.svg";
import MoreSvg from "@/assets/icons/svg/more.svg";
import { Message, Video } from "@/types/ask";
import { MaterialItem } from "@/types/personal-info";
import { useVideoPlayer, VideoView } from 'expo-video';
import React from 'react';
import {
    Image,
    Modal,
    Pressable,
    StyleProp,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    ViewStyle
} from 'react-native';
import { ThemedText } from "../ThemedText";
import TypewriterText from "./typewriterText";
import { mergeArrays } from "./utils";

interface RenderMessageProps {
    item: Message;
    sessionId: string;
    setModalVisible: React.Dispatch<React.SetStateAction<{ visible: boolean, data: Video | MaterialItem }>>;
    modalVisible: { visible: boolean, data: Video | MaterialItem };
}

const renderMessage = ({ item, sessionId, setModalVisible, modalVisible }: RenderMessageProps) => {
    const isUser = item.role === 'User';
    const isVideo = (data: Video | MaterialItem): data is Video => {
        return 'video' in data;
    };

    // 创建一个新的 VideoPlayer 组件
    const VideoPlayer = ({
        videoUrl,
        style,
        onPress
    }: {
        videoUrl: string;
        style?: StyleProp<ViewStyle>;
        onPress?: () => void;
    }) => {
        const player = useVideoPlayer(videoUrl, (player) => {
            player.loop = true;
            player.play();
        });

        return (
            <Pressable
                style={[{
                    flex: 1,
                    justifyContent: 'center',
                    alignItems: 'center',
                }, style]}
                onPress={onPress}
            >
                <VideoView
                    style={{
                        width: '100%',
                        height: '100%',
                        backgroundColor: '#000',  // 添加背景色
                    }}
                    player={player}
                    allowsFullscreen
                    allowsPictureInPicture
                />
            </Pressable>
        );
    };

    return (
        <View className={`flex-row items-start gap-2 w-full ${isUser ? 'justify-end' : 'justify-start'}`}>
            {!isUser && <ChatSvg width={36} height={36} />}
            <View className="max-w-[90%] mb-[1rem] flex flex-col gap-2">
                <View
                    style={[
                        styles.messageBubble,
                        isUser ? styles.userBubble : styles.aiBubble
                    ]}
                    className={`${isUser ? '!bg-bgPrimary ml-10 rounded-full' : '!bg-aiBubble mr-10 rounded-2xl'} border-0 ${!isUser && (item.content.video_material_infos && item.content.video_material_infos.length > 0 || item.content.image_material_infos && item.content.image_material_infos.length > 0) ? '!rounded-t-3xl !rounded-b-2xl' : '!rounded-3xl'}`}
                >
                    <View className={`${isUser ? 'bg-bgPrimary' : 'bg-aiBubble'}`}>
                        <Text style={isUser ? styles.userText : styles.aiText}>
                            {!isUser
                                ?
                                sessionId ? item.content.text : <TypewriterText text={item.content.text} speed={100} loop={item.content.text == "正在寻找，请稍等..."} />
                                : item.content.text
                            }
                        </Text>

                        {(item.content.image_material_infos && item.content.image_material_infos.length > 0 || item.content.video_material_infos && item.content.video_material_infos.length > 0) && (
                            <View className="relative">
                                <View className="mt-2 flex flex-row gap-2 w-full">
                                    {mergeArrays(item.content.image_material_infos || [], item.content.video_material_infos || [])?.slice(0, 3)?.map((image, index, array) => (
                                        <Pressable
                                            key={image.id}
                                            onPress={() => {
                                                setModalVisible({ visible: true, data: image });
                                            }}
                                            style={({ pressed }) => [
                                                array.length === 1 ? styles.fullWidthImage : styles.gridImage,
                                                array.length === 2 && { width: '49%' },
                                                array.length >= 3 && { width: '32%' },
                                                { opacity: pressed ? 0.8 : 1 } // 添加按下效果
                                            ]}
                                        >
                                            <Image
                                                source={{ uri: image?.preview_file_info?.url || image.video?.preview_file_info?.url }}
                                                className="rounded-xl w-full h-full"
                                                resizeMode="cover"
                                            />
                                        </Pressable>
                                    ))}
                                </View>
                                {
                                    ((item.content.video_material_infos?.length || 0) + (item.content.image_material_infos?.length || 0)) > 3
                                    && <View className="absolute top-1/2 -translate-y-1/2 -right-4 translate-x-1/2 bg-bgPrimary flex flex-row items-center gap-2 p-1 pl-2 rounded-full">
                                        <ThemedText className="!text-white font-semibold">{((item.content.video_material_infos?.length || 0) + (item.content.image_material_infos?.length || 0))}</ThemedText>
                                        <View className="bg-white rounded-full p-2">
                                            <MoreSvg />
                                        </View>
                                    </View>
                                }
                            </View>
                        )}
                    </View>
                </View>
                {item.askAgain && item.askAgain.length > 0 && (
                    <View className={`mr-10`}>
                        {item.askAgain.map((suggestion, index, array) => (
                            <TouchableOpacity
                                key={suggestion.id}
                                className={`bg-yellow-50 rounded-xl px-4 py-2 border border-yellow-200 border-0 mb-2 ${index === array.length - 1 ? 'mb-0 rounded-b-3xl rounded-t-2xl' : 'rounded-2xl'}`}
                            >
                                <Text className="text-gray-700">{suggestion.text}</Text>
                            </TouchableOpacity>
                        ))}
                    </View>
                )}
                <Modal
                    animationType="fade"
                    transparent={true}
                    visible={modalVisible.visible}
                    onRequestClose={() => {
                        setModalVisible({ visible: false, data: {} as Video | MaterialItem });
                    }}>
                    <View style={styles.centeredView}>
                        <TouchableOpacity
                            style={styles.background}
                            onPress={() => {
                                setModalVisible({ visible: false, data: {} as Video | MaterialItem })
                            }}
                        />
                        <TouchableOpacity style={styles.modalView} onPress={() => setModalVisible({ visible: false, data: {} as Video | MaterialItem })}>
                            {isVideo(modalVisible.data) ? (
                                // 视频播放器
                                <TouchableOpacity
                                    activeOpacity={1}
                                    style={{
                                        flex: 1,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                        maxHeight: "60%",
                                    }}
                                    onPress={() => setModalVisible({ visible: false, data: {} as Video | MaterialItem })}
                                >
                                    <VideoPlayer
                                        videoUrl={modalVisible.data.video.file_info.url}
                                        style={{
                                            width: '100%',
                                            height: '100%',
                                            alignSelf: 'center',
                                            justifyContent: 'center',
                                        }}
                                        onPress={() => setModalVisible({ visible: false, data: {} as Video | MaterialItem })}
                                    />
                                </TouchableOpacity>
                            ) : (
                                // 图片预览
                                <TouchableOpacity
                                    activeOpacity={1}
                                    onPress={() => setModalVisible({ visible: false, data: {} as Video | MaterialItem })}
                                    style={styles.imageContainer}
                                >
                                    <Image
                                        source={{ uri: modalVisible.data.preview_file_info?.url }}
                                        style={styles.fullWidthImage}
                                        resizeMode="contain"
                                    />
                                </TouchableOpacity>
                            )}
                        </TouchableOpacity>
                    </View>
                </Modal>
            </View>
        </View>
    );
};

export default renderMessage;

const styles = StyleSheet.create({
    video: {
        width: '100%',
        height: '100%',
    },
    imageContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        maxHeight: '60%',
    },
    fullWidthImage: {
        width: '100%',
        height: "54%",
        marginBottom: 8,
    },
    gridImage: {
        aspectRatio: 1,
        marginBottom: 8,
    },
    background: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0, 0, 0, 0.5)', // 添加半透明黑色背景
    },
    centeredView: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalView: {
        borderRadius: 20,
        alignItems: 'center',
        height: '100%',
        width: "100%",
        justifyContent: 'center',
        alignSelf: 'center',
    },
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    userAvatar: {
        width: 30,
        height: 30,
        borderRadius: 15,
    },
    messageList: {
        padding: 16,
    },
    messageBubble: {
        paddingHorizontal: 16,
        paddingVertical: 12,
        fontWeight: "600"
    },
    userBubble: {
        alignSelf: 'flex-end',
        backgroundColor: '#FFB645',
        marginLeft: '20%',
    },
    aiBubble: {
        alignSelf: 'flex-start',
        backgroundColor: '#fff',
        marginRight: '20%',
        borderWidth: 1,
        borderColor: '#e5e5ea',
    },
    userText: {
        color: '#4C320C',
        fontSize: 16,
    },
    aiText: {
        color: '#000',
        fontSize: 16,
    },
});