import { FontAwesome } from "@expo/vector-icons";
import React, { MutableRefObject } from "react";
import { FlatList, Keyboard, ListRenderItem, StyleSheet, Text, TextInput, View } from "react-native";
import { LMComment } from "../../../../hooks/useComments";
import { CommentView } from "./CommentView";

interface CommentsContainerProps {
    focusedCommentId?: string,
    comments?: LMComment[],
    focusComment: (id: string) => void,
    startEditingComment: (comment: LMComment) => void,
    deleteComment: (id: string) => void
    commentBeingEdited?: LMComment, 
    setCommentBeingEdited: (comment: LMComment) => void,
    setNewComment: (commentId: string) => void,
    newCommentId?: string,
    editComment: (comment: LMComment) => void,
    addComment: () => void
    commentListRef: MutableRefObject<FlatList>
    commentTextInputRef: MutableRefObject<TextInput>
    setKeyboardOpened: (state: boolean) => void
    keyboardOpened: boolean
}

/**
 * Renders all [comments]{@link LMComment} associated with the {@linkcode selectedLandmark} as items for the [FlatList]{@link https://reactnative.dev/docs/flatlist} in this component.
*/
export const CommentsContainer: React.FC<CommentsContainerProps> = (props) => {

    /**
     * Flatlist render item method for each comment. 
     * @param 
     * @returns 
     */
    const renderComment: ListRenderItem<LMComment> = ({item, index}) => {
        const selected = item.id == props.focusedCommentId;
        const belowSelected = props.comments[index - 1]?.id == props.focusedCommentId;
        const latestComment = index == 0;
        return (
            <View>
                {/* Some conditional rendering to make the borders look nice */}
                {latestComment ? null : <View style={[selected || belowSelected ? {marginVertical: 0} : {marginHorizontal: 10}, {height: 1, borderBottomWidth: 1, borderColor: 'lightgray'}]}></View> }
                <CommentView comment={item} selected={selected} focusComment={props.focusComment} startEditingComment={props.startEditingComment} deleteComment={props.deleteComment} />
            </View>
        );
    };

    /**
     * || DEPRECATED ||
     * Sets a flag that tracks whether keyboard is shown
     */
    // React.useEffect(() => {
    //     if (Platform.OS == 'android') {
    //         Keyboard.addListener('keyboardDidShow', () => props.setKeyboardOpened(true))
    //         Keyboard.addListener('keyboardDidHide', clearStateOnKeybordDismiss);
    //     }
    
    //     // cleanup function
    //     return () => {
    //       Keyboard.removeAllListeners('keyboardDidHide');
    //       Keyboard.removeAllListeners('keyboardDidShow');
    //     };
    //   }, []);

    /**
     * || DEPRECATED ||
     * Clears out the comment input if keyboard is dismissed without posting the comment **DEPRECATED**
     */
    // const clearStateOnKeybordDismiss = () => {
    //     props.setKeyboardOpened(false)
    //     props.setCommentBeingEdited(undefined);
    //     if (props.commentBeingEdited) {
    //         props.setCommentBeingEdited(undefined);
    //     }
    //     if (props.newCommentId) {
    //         props.setNewComment('');
    //     }
    // }

    /**
     * Simple check to see if the landmark has any comments
     */
    const hasComments = () => {
        return props.comments?.length > 0
    }

    return (  
    <View style={[styles.commentContainer, {borderBottomWidth: 1, borderColor: 'lightgray', paddingBottom: 30}]}>
        {hasComments() ? 
        <>
            <Text style={{color: 'white', marginBottom: 20}}>Comments: </Text>
            <FlatList<LMComment>
                nestedScrollEnabled={true}
                ref={props.commentListRef}
                keyExtractor={i => i.id}
                data={props.comments} 
                extraData={props.focusedCommentId}
                renderItem={renderComment}
                style={{backgroundColor: 'white'}}
                getItemLayout={(data, index) => ({length: props.comments.length, offset: props.comments.length * index, index})}/>
        </> : 
        <Text style={{marginVertical: 20, color: 'white'}}>Be the first to comment on this landmark</Text> }
        <View style={{height: 1, borderBottomWidth: 1, borderColor: 'lightgray'}}></View>
        <View style={{flexDirection: 'row', backgroundColor: 'white', paddingRight: 15}}>
            <TextInput 
                ref={props.commentTextInputRef}
                placeholder="Add comment..." 
                onChangeText={props.commentBeingEdited ? value => props.setCommentBeingEdited({...props.commentBeingEdited, content: value}) : value => props.setNewComment(value)} 
                value={props.commentBeingEdited ? props.commentBeingEdited.content : props.newCommentId}
                placeholderTextColor="gray" 
                style={{padding: 10, flex: 5}}
                multiline={true} />
            {props.newCommentId || props.commentBeingEdited ? 
            <View style={{alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row', flex: 1}}>
                <FontAwesome name="times" size={20} color="lightgray" style={{ backgroundColor: 'white',  }} onPress={Keyboard.dismiss} />
                {props.commentBeingEdited ?
                <FontAwesome name="check" size={20} style={{ marginLeft: 15, marginRight: 15, backgroundColor: 'white', padding: 'auto'}} onPress={async () => props.editComment(props.commentBeingEdited)} /> :
                <FontAwesome name="paper-plane" size={20} style={{ backgroundColor: 'white', padding: 'auto'}} onPress={async () => props.addComment()} /> }
            </View> : null}
        </View>
    </View>)
}

const styles = StyleSheet.create({
    input: {
        padding: 5,
        color: 'black'
    },
    commentContainer: {
        flex: 5,
        marginBottom: 40,
    },
})