import ReturnArrow from "@/assets/icons/svg/returnArrow.svg";
import Chat from "@/components/ask/chat";
import AskHello from "@/components/ask/hello";
import SendMessage from "@/components/ask/send";
import { ThemedText } from "@/components/ThemedText";
import { fetchApi } from "@/lib/server-api-util";
import { Message } from "@/types/ask";
import { router, useFocusEffect, useLocalSearchParams } from "expo-router";
import { useCallback, useEffect, useRef, useState } from 'react';
import {
    Animated,
    FlatList,
    Keyboard,
    KeyboardAvoidingView,
    Platform,
    StyleSheet,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import { useSafeAreaInsets } from "react-native-safe-area-context";

export default function AskScreen() {
    const insets = useSafeAreaInsets();

    const chatListRef = useRef<FlatList>(null);
    const [isHello, setIsHello] = useState(true);
    const [conversationId, setConversationId] = useState<string | null>(null);
    const [userMessages, setUserMessages] = useState<Message[]>([]);
    const [selectedImages, setSelectedImages] = useState<string[]>([]);
    const fadeAnim = useRef(new Animated.Value(1)).current;
    const fadeAnimChat = useRef(new Animated.Value(0)).current;

    const { sessionId, newSession } = useLocalSearchParams<{
        sessionId: string;
        newSession: string;
    }>();

    // 创建一个可复用的滚动函数
    const scrollToEnd = useCallback((animated = true) => {
        if (chatListRef.current) {
            setTimeout(() => chatListRef.current?.scrollToEnd({ animated }), 100);
        }
    }, []);

    useEffect(() => {
        if (!isHello && userMessages.length > 0) {
            scrollToEnd();
        }
    }, [userMessages, isHello, scrollToEnd]);

    useEffect(() => {
        const keyboardDidShowListener = Keyboard.addListener(
            'keyboardDidShow',
            (e) => {
                setTimeout(() => {
                    if (!isHello) {
                        scrollToEnd();
                    }
                }, 100);
            }
        );

        const keyboardDidHideListener = Keyboard.addListener(
            'keyboardDidHide',
            () => {
                setTimeout(() => {
                    if (!isHello) {
                        scrollToEnd(false);
                    }
                }, 100);
            }
        );

        return () => {
            keyboardDidShowListener.remove();
            keyboardDidHideListener.remove();
        };
    }, [isHello]);

    useEffect(() => {
        if (sessionId) {
            setConversationId(sessionId);
            setIsHello(false);
            fetchApi<Message[]>(`/chats/${sessionId}/message-history`).then((res) => {
                setUserMessages(res);
            });
        }
        if (newSession) {
            setIsHello(true);
            setConversationId(null);
        }
    }, [sessionId, newSession]);

    useEffect(() => {
        if (isHello) {
            Animated.parallel([
                Animated.timing(fadeAnim, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.timing(fadeAnimChat, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                })
            ]).start();
        } else {
            Animated.parallel([
                Animated.timing(fadeAnim, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.timing(fadeAnimChat, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                })
            ]).start(() => {
                setTimeout(() => {
                    if (!isHello) {
                        scrollToEnd(false);
                    }
                }, 50);
            });
        }
    }, [isHello, fadeAnim, fadeAnimChat]);

    useEffect(() => {
        if (!isHello) {
            // 不再自动关闭键盘，让用户手动控制
            // 这里可以添加其他需要在隐藏hello界面时执行的逻辑
            scrollToEnd(false);
        }
    }, [isHello]);

    useFocusEffect(
        useCallback(() => {
            setIsHello(true);
            setUserMessages([])
        }, [])
    );

    return (
        <View style={[styles.container, { paddingTop: insets.top }]}>
            {/* 导航栏 */}
            <View style={[styles.navbar, isHello && styles.hiddenNavbar]}>
                <TouchableOpacity
                    style={styles.backButton}
                    onPress={() => {
                        try {
                            if (TextInput.State?.currentlyFocusedInput) {
                                const input = TextInput.State.currentlyFocusedInput();
                                if (input) input.blur();
                            }
                        } catch (error) {
                            console.log('失去焦点失败:', error);
                        }
                        Keyboard.dismiss();
                        router.push('/memo-list');
                    }}
                >
                    <ReturnArrow />
                </TouchableOpacity>
                <ThemedText style={styles.title}>MemoWake</ThemedText>
                <View style={styles.placeholder} />
            </View>

            <View style={styles.contentContainer}>
                {/* 欢迎页面 */}
                <Animated.View
                    style={[
                        styles.absoluteView,
                        {
                            opacity: fadeAnim,
                            pointerEvents: isHello ? 'auto' : 'none',
                            zIndex: 1
                        }
                    ]}
                >
                    <AskHello />
                </Animated.View>

                {/* 聊天页面 */}
                <Animated.View
                    style={[
                        styles.absoluteView,
                        {
                            opacity: fadeAnimChat,
                            pointerEvents: isHello ? 'none' : 'auto',
                            zIndex: 0
                        }
                    ]}
                >
                    <Chat
                        ref={chatListRef}
                        userMessages={userMessages}
                        sessionId={sessionId}
                        setSelectedImages={setSelectedImages}
                        selectedImages={selectedImages}
                        style={styles.chatContainer}
                        contentContainerStyle={styles.chatContentContainer}
                        showsVerticalScrollIndicator={false}
                        onContentSizeChange={() => scrollToEnd()}
                    />
                </Animated.View>
            </View>

            {/* 输入框区域 */}
            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                keyboardVerticalOffset={0} >
                <View style={styles.inputContainer} key={conversationId}>
                    <SendMessage
                        setIsHello={setIsHello}
                        conversationId={conversationId}
                        setConversationId={setConversationId}
                        setUserMessages={setUserMessages}
                        selectedImages={selectedImages}
                        setSelectedImages={setSelectedImages}
                    />
                </View>
            </KeyboardAvoidingView>
        </View >
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f8f8f8',
    },
    navbar: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingVertical: 16,
        paddingHorizontal: 16,
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0,0,0,0.1)',
        elevation: 1, // Android
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.1,
        shadowRadius: 1,
    },
    hiddenNavbar: {
        shadowOpacity: 0,
        elevation: 0,
    },
    backButton: {
        padding: 8,
        marginRight: 8,
    },
    title: {
        fontSize: 20,
        fontWeight: '600',
        textAlign: 'center',
        flex: 1,
    },
    placeholder: {
        width: 40,
    },
    contentContainer: {
        flex: 1,
        position: 'relative'
    },
    absoluteView: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'white',
    },
    chatContainer: {
        flex: 1,
    },
    chatContentContainer: {
        paddingBottom: 20,
    },
    inputContainer: {
        padding: 16,
        paddingBottom: 24,
        backgroundColor: 'white',
        // borderTopWidth: 1,
        // borderTopColor: '#f0f0f0',
    },
});