import { View, Text, TextInput, TouchableOpacity, Image, ScrollView, Keyboard, Button } from "react-native";
import React, { useEffect, useRef, useState } from "react";
import { styles } from "./HelpHub.styles";
import { HelpHubChatTypes } from "./HelpHub.types";

import CrossIcon from "../../assets/ReactSVG/CrossIcon";
import SearchIcon from "../../assets/ReactSVG/SearchIcon";
import DownArrow from "../../assets/ReactSVG/DownArrow";
import ErrorIconNew from "../../assets/ReactSVG/ErrorIconNew";
import QuestLogo from "../../assets/ReactSVG/QuestLogo";
import AttechIcon from "../../assets/ReactSVG/AttechIcon";
import InputFaceIcon from "../../assets/ReactSVG/InputFaceIcon";
import InputSendIcon from "../../assets/ReactSVG/InputSendIcon";

type ChatMessage = {
    sender?: string;
    receiver?: string;
};
const ChatTabScreen = (props: HelpHubChatTypes) => {
    const { contentConfig, handleToggleTabBar,styleConfig } = props;

    const [showPersonalChat, setShowPersonalChat] = useState(false);
    const [message, setMessage] = useState("");
    const [data, setData] = useState<ChatMessage[]>([]);
    const scrollViewRef = useRef<ScrollView>(null); // Ref for ScrollView

    const [chat, setChats] = useState([
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
        {
            profile: "hi",
            senderName: "Alexander Rodriguez...",
            senderMessage:
                " I don't have personal preferences, but I can recommend books based on your interests. What genre are you into? For a cultural experience, Kyoto in Japan is fantastic.",
        },
    ]);
    const handleSendButtonClick = () => {
        setShowPersonalChat(true)
        handleToggleTabBar(false);
    };

    const handleMessageSend = () => {
        if (message.trim() !== '') {
            setData(prevData => [
                ...prevData,
                { sender: message },
                { receiver: "I am not in the mood to answer, you come back later" }
            ]);
            setMessage('');
            Keyboard.dismiss(); 
        }
    };

    const scrollToEnd = () => {
        if (scrollViewRef.current) {
            scrollViewRef.current.scrollToEnd({ animated: true });
        }
    };
    
    // const handleScroll = (event: any) => {
    //     const { contentOffset, layoutMeasurement, contentSize } = event.nativeEvent;
    //     setIsScrolledToBottom(contentOffset.y >= contentSize.height - layoutMeasurement.height);
    // };


    return (
        <>
            {!showPersonalChat && (
                <View style={[styles.tasksMainViewStyle,styleConfig?.Chat?.Form]}>
                    <View style={[styles.tasksHeaderViewStyle]}>
                        <View style={[styles.tasksHeaderInnerViewStyle]}>
                            <Text style={[styles.tasksHeaderTextStyle,styleConfig?.Chat?.Topbar?.Heading]}>
                                {contentConfig?.heading || "Chats"}

                            </Text>
                            <CrossIcon size={10} color="#939393" />
                        </View>
                        <Text style={[styles.tasksHeaderDescriptionStyle,,styleConfig?.Chat?.Topbar?.SubHeading]}>
                            {contentConfig?.subHeading || "Welcome back, Please talk to us to understand"}
                        </Text>
                    </View>

                    <View style={[styles.tasksTabListViewStyle]}>

                        {/* Search bar */}
                        <View style={[styles.searchViewStyle,styleConfig?.Chat?.Searchbox]}>
                            <TextInput
                                style={[styles.inputViewStyle]}
                                // onChangeText={handleSearch}
                                placeholder="Search for FAQs..."
                            />
                            <SearchIcon />
                        </View>

                        {/* Chats */}
                        <View style={{ flex: 1, alignItems: "center", gap: 12, }}>
                            {/* only one chat */}

                            {/* {chat.map((value, index) => {
                                    return (
                                        <View >
                                            <View >
                                                
                                                <Text>
                                                {value.profile}
                                                </Text>
                                            </View>

                                            <View >
                                                <View
                                                    
                                                
                                                >
                                                    <Text> {value.senderName}</Text>
                                                   
                                                </View>
                                                <View
                                                   
                                                >
                                                    <Text>
                                                    {value.senderMessage}
                                                    </Text>
                                                    
                                                </View>
                                            </View> */}

                            {/* <Button
                                                className="q-helphub-chat-btn"
                                                onClick={() => setShowPersonalChat((prev) => !prev)}
                                            >
                                                <img src={OpenSectionButton} alt="" />
                                            </Button> */}
                            {/* </View>
                                    );
                            })}
                                 */}
                        </View>

                        <View>
                            <TouchableOpacity onPress={handleSendButtonClick} style={[styles.chatButton,styleConfig?.Chat?.chatButton]}>
                                <Text style={[styles.chatButtonText,styleConfig?.Chat?.chatButtonText]}>Send a message</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}

            {showPersonalChat && (
                <View style={styles.tasksMainViewStyle}>
                    {/* Header */}
                    <View style={[styles.privetChatHeaderStyle]}>
                        <TouchableOpacity style={{ transform: [{ rotate: "90deg" }] }} onPress={() => { handleToggleTabBar(true); setShowPersonalChat(false) }}>
                            <DownArrow />
                        </TouchableOpacity>
                        <Text style={[styles.privetChatHeaderTextStyle,styleConfig?.Chat?.privetChatHeaderTextStyle]}>
                            Questlabs chats
                        </Text>
                        <ErrorIconNew />
                    </View>


                    {/* Chats */}
                    <ScrollView ref={scrollViewRef} 
                        style={{ padding: 20 }}
                        onContentSizeChange={scrollToEnd} 
                        // onScroll={handleScroll}
                 >
                        <View style={[styles.privetChatIconView]}>
                            {/* chats icon */}
                            <View style={[styles.privetChatIconInnerView]}>
                                <Image
                                    style={[styles.ChatheaderLeftImageStyle]}
                                    source={require("../../assets/UserDemo.png")}
                                />
                                <View style={[styles.chatIconView]}>

                                    <QuestLogo size={30} fill="#FFF" />
                                </View>
                                <Image
                                    style={[styles.ChatheaderRightImageStyle]}
                                    source={require("../../assets/UserDemo.png")}
                                />
                            </View>
                            <Text style={[styles.chatTitleText,styleConfig?.Chat?.chatTitleText]}>
                                General feedback
                            </Text>
                            <Text style={[styles.chatTitleDescription,styleConfig?.Chat?.chatTitleDescription]}>Give general feedback of this page</Text>
                        </View>

                        {/* Chating */}
                        <View style={{ paddingVertical: 20 }}>
                            {data && data.map((message, index) => (
                                <View style={{ position: "relative", flexDirection: "row", justifyContent: message.sender ? "flex-end" : "flex-start", alignItems: "center", marginBottom: 10 }} key={index}>
                                    {message.receiver && (
                                        <View style={[styles.receiverChatIconView]}>
                                            <QuestLogo size={14} />
                                        </View>
                                    )}

                                    <View style={[styles.message,styleConfig?.Chat?.message, message.sender ? styles.sender : styles.receiver]}>
                                        <Text>{message.sender ? message.sender : message.receiver}</Text>
                                    </View>

                                    {message.sender && (
                                        <View style={[styles.senderChatIconView]}>
                                            {/* <Image style={{ width: 28, height: 28 }} source={require("../../assets/UserDemo.png")} /> */}
                                            <QuestLogo size={14} />
                                        </View>
                                    )}
                                </View>
                            ))}
                        </View>
                    </ScrollView>


                    {/* inputs */}
                    <View style={[styles.chatInputViewStyle,styleConfig?.Chat?.chatInputViewStyle]}>
                        <TextInput
                            style={[styles.inputViewStyle]}
                            onChangeText={text => setMessage(text)}
                            value={message}
                            placeholder="Ask a qustions..."
                            onSubmitEditing={handleMessageSend} // Call handleMessageSend when Enter is pressed
                        />
                        <InputFaceIcon />
                        <AttechIcon />
                        <TouchableOpacity onPress={handleMessageSend}>
                            <InputSendIcon />

                        </TouchableOpacity>
                    </View>
                </View>
            )}
        </>

    );
};

export default ChatTabScreen;
