import React, { FunctionComponent, useEffect, useState } from 'react';
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    Text,
    TextStyle,
    TouchableOpacity,
    View,
    ViewStyle,
} from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { IStyledProps } from '../common/types';
import { updateBubbleInfo, modifyBubbleImage } from '../../store/bubbles/bubblesSlice';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { ImageHolder } from '../common/ImageHolder';
import { launchImageLibrary } from 'react-native-image-picker';
import { Header } from '../common/Header';
import { EditBubbleNavigationProp, EditBubbleRouteProp } from '../../RootStackParamList';
import { useAppDispatch } from '../../store/hooks';
import { IconButton, TextInput } from 'react-native-paper';


interface IEditBubbleProps extends IStyledProps<IBubblesStyleProps> {
    renderChangeBubbleInfo?: () => React.ReactElement;
    navigation: EditBubbleNavigationProp;
    route: EditBubbleRouteProp;
}
interface IBubblesStyleProps {
    headerBgColor?: ViewStyle;
    input?: ViewStyle;
    container?: ViewStyle;
    inputContainer?: ViewStyle;
    warningContainer?: ViewStyle;
    warningText?:TextStyle;
    errorText?: TextStyle;
    notValidName?: ViewStyle;
    bubbleInfo?: ViewStyle;
    profilePic?: ViewStyle;
    loader?: ViewStyle;
    textStyle?: TextStyle;
    modifyText?: TextStyle;
}

export const EditBubble: FunctionComponent<IEditBubbleProps> = ({
    style,
    renderChangeBubbleInfo,
    navigation,
    route
}) => {
    const bubble = route.params.bubble;
    const mergedStyle = { ...defaultStyle, ...style };
    const [bubbleName, setBubbleName] = useState(bubble.name);
    const [bubbleTopic, setBubbleTopic] = useState(bubble.topic);
    const [bubblePhoto, setBubblePhoto] = useState(bubble.imageURL);
    const [loading, setLoading] = useState<boolean>(false);
    const [validBubbleName, setValidBubbleName] = useState(true);
    const dispatch = useAppDispatch()

    useEffect(() => {
        const updateBubbleListener = eventEmitter.addListener(
            EventType.UpdateBubbleResult,
            (eventData: string) => {
                if (eventData !== 'success') {
                    Alert.alert('Failure', Strings.updateBubbleInfoFailure);
                }
                navigation.pop();
            });

        const newBubbleImageListener = eventEmitter.addListener(
            EventType.NewBubbleImage, (eventData: string) => {
                setLoading(false);
                setBubblePhoto(eventData)
            });

        const updateBubbleImageListener = eventEmitter.addListener(
            EventType.UpdateBubbleImageResult,
            (eventData: string) => {
                setLoading(false);
                if (eventData !== 'success') {
                    Alert.alert('Failure', Strings.updateBubbleImageFailure);
                }
                navigation.pop();

            });

        return () => {
            updateBubbleListener.remove();
            newBubbleImageListener.remove();
            updateBubbleImageListener.remove()
        }
    }, []);

    const onClickUpdateInfo = () => {
        setLoading(true);
        dispatch(updateBubbleInfo({bubbleId: bubble.id , name: bubbleName, topic: bubbleTopic}));
    };
    const onBubbleNameChange = (name: string) => {
        setBubbleName(name);
        if (name.length < 3 || name.length === 0) {
            setValidBubbleName(false);
        } else {
            setValidBubbleName(true);
        }
    };
    const onBubbleTopicChange = (topic: string) => {
        setBubbleTopic(topic);
    };

    const updateBubbleImage = () => {
        launchImageLibrary({
            quality: 1.0,
            selectionLimit: 1,
            mediaType: 'mixed',
            includeBase64: false,
        }, response => {
            if (response.assets && response.assets!.length > 0) {
                const fileUri = response.assets![0].uri;
                if (fileUri)
                    dispatch(modifyBubbleImage({bubbleId: bubble.id , imageUrl: fileUri}))
            }
        });

    }
    const renderBubbleInfo = () => {
        if (renderChangeBubbleInfo) {
            return renderChangeBubbleInfo();
        }
        else {
            return (
                <View style={mergedStyle.bubbleInfo}>
                <TouchableOpacity style={mergedStyle.profilePic} onPress={updateBubbleImage}>
                <ImageHolder url={bubblePhoto} name={bubble.name} />
                <Text style={mergedStyle.modifyText}>Modify</Text>
                </TouchableOpacity>
    
                <View style={mergedStyle.inputContainer}>
                    <TextInput
                        mode="outlined"
                        placeholder="Enter name"
                        style={mergedStyle.input}
                        onChangeText={onBubbleNameChange}
                        error={!validBubbleName} // Use error prop for validation
                    />
                    {!validBubbleName && (
                        <View style={mergedStyle.warningContainer}>
                            <Text style={mergedStyle.warningText}>!</Text>
                            <Text style={mergedStyle.errorText}>{Strings.bubbleNameException}</Text>
                        </View>
                    )}
                    <TextInput
                        mode="outlined"
                        placeholder={Strings.bubbleTopic}
                        style={mergedStyle.input}
                        onChangeText={onBubbleTopicChange}
                    />
                </View>
            </View>
            );
        }
    };
    const renderCenterHeader = () => {
        return <Text style={{color: 'white'}}>{bubble.name} </Text>;
    }
    const renderRightHeader = () => {
        if (validBubbleName)
            return <IconButton icon="checkmark" size={50} iconColor="white" onPress={onClickUpdateInfo} />
        else return null;
    }
    return (
        <View style={mergedStyle.container}>
            <Header
                containerStyle={defaultStyle.headerBgColor}
                rightComponent={renderRightHeader}
                centerComponent={renderCenterHeader}
                centerContainerStyle={{ alignItems: 'center' }}
            />
            {renderBubbleInfo()}
            {loading && (
                <View style={mergedStyle.loader}>
                    <ActivityIndicator color="#0086CF" size="large" />
                </View>
            )}
        </View>
    );
};

const defaultStyle: IBubblesStyleProps = {
    loader: {
        flex: 1,
        justifyContent: 'center',
        opacity: 1,
        position: 'absolute',
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,
        backgroundColor: 'rgba(234, 236, 238, 0.8)',
    },
    container: {
        flex: 1,
        backgroundColor: '#ffffff',
        height: 'auto',
    },
    textStyle: {
        textAlign: 'center',
        fontSize: 10,
        color: '#fff',
        backgroundColor: 'gray',
        opacity: 1,
        position: 'absolute',
        width: 100,
        marginTop: 70,
    },
    bubbleInfo: {
        padding: 10,
    },
    profilePic: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
    },
    modifyText: {
        marginLeft: 10,
        color: 'blue',
    },
    inputContainer: {
        justifyContent: 'space-around',
    },
    input: {
        marginBottom: 10,
    },
    warningContainer: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    warningText: {
        backgroundColor: 'red',
        color: 'white',
        borderRadius: 10,
        padding: 2,
        marginRight: 5,
        textAlign: 'center',
        width: 20, // Adjust width for a better appearance
    },
    errorText: {
        color: 'red',
        fontSize: 12,
    },
};