import React, { useEffect, FunctionComponent, useContext, useState, forwardRef, useRef, MutableRefObject } from 'react';
import { View, ViewStyle, TextInput, Linking, InteractionManager, Image } from 'react-native';
import styles from './AnswerModalStyles';
import useAnswerModalTranslation from './AnswerModalTranslation'
import { PixelStyles } from 'react-native-pixel-styles';
import Modal from 'react-native-modal';
import { isIphoneX, isAndroid } from 'react-native-pixel-styles/Utils/DevicesUtils';
import { PixelwolfText, PixelScaleButton } from 'react-native-pixel-components';
import { PixelAnswer } from '../../Model/PixelAnswer';
import { PixelRichTextEditor } from '../PixelRichTextEditor/PixelRichTextEditor';
import { throttle } from 'lodash'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { useKeyboard } from '@react-native-community/hooks';
import * as Animatable from 'react-native-animatable'
interface IProps {
    // Props type definition
    style?: ViewStyle | ViewStyle[]
}

interface IState {
    // State type definition
    isVisible: boolean
    currentAnswer: PixelAnswer
    answerText: string
    formattedAnswer: React.ReactNode
}

export const AnswerModal: FunctionComponent<IProps> = (props) => {

    const { I18n } = useAnswerModalTranslation()
    const themeStore = useContext(PixelStyles.pixelThemeStoreContext)
    const textInput: MutableRefObject<TextInput> = useRef(null)
    const keyboard = useKeyboard()

    const initialState: IState = {
        isVisible: true,
        currentAnswer: null,
        answerText: null,
        formattedAnswer: null
    };

    const [isVisible, setIsVisible] = useState(initialState.isVisible)
    const [currentAnswer, setCurrentAnswer] = useState(initialState.currentAnswer)
    const [answerText, setAnswerText] = useState(initialState.answerText)
    const [formattedAnswer, setFormattedAnswer] = useState(initialState.formattedAnswer)

    // ComponentDidMount
    useEffect(() => {
        InteractionManager.runAfterInteractions(() => {
            if (textInput && textInput.current) {
                textInput.current.focus()
            }
        })
        return () => {
            //ComponentDidUnmount
        }
    }, [])

    const formatText = (text) => {
        if (text) {
            const regex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/g
            const splittedText = text.split(regex)
            console.log('splitted', splittedText)
            setFormattedAnswer(splittedText.map((sentence) => {
                if (sentence.match(regex)) {
                    return <PixelwolfText color={themeStore.theme.primary} >
                        {sentence}
                    </PixelwolfText>
                }
                return sentence
            }))
        }
    }
    const throttledUpdateLinks = useRef(throttle(formatText, 2000))

    useEffect(() => throttledUpdateLinks.current(answerText), [answerText])

    const openModal = (answer: PixelAnswer) => {
        setCurrentAnswer(answer)
        setIsVisible(true)
    }

    const closeAnswerModal = () => {
        setIsVisible(false)
    }

    const onSendPressed = () => {

    }

    const onTextChanged = (text: string) => {
        setAnswerText(text)
    }

    return (
        <Modal propagateSwipe={true} style={[styles.fullContainer, { margin: 0 }, themeStore.getMainBackgroundStyle]} swipeDirection={'down'} onSwipeComplete={closeAnswerModal} isVisible={isVisible}>
            <View style={[styles.fullWidthContainer, themeStore.getSecondaryBackground, styles.centeredRow, styles.paddingHorizontal, styles.bigPaddingTop, styles.smallPaddingBottom, styles.spaceBetween, isIphoneX && { paddingTop: 50 }]}>
                <PixelwolfText onPress={closeAnswerModal} size={'b15'} color={themeStore.theme.mainTextColor}>
                    {I18n.translation.Close}
                </PixelwolfText>
                <PixelwolfText onPress={onSendPressed} size={'b15'} weight={'semibold'} color={themeStore.theme.mainTextColor}>
                    {I18n.translation.Send}
                </PixelwolfText>
            </View>
            <KeyboardAwareScrollView style={[styles.flex1, styles.padding]} contentContainerStyle={[styles.bigPaddingBottom]}>
                <TextInput
                    ref={textInput}
                    style={[styles.fullContainer, styles.text15, { fontFamily: themeStore.fontFamily.primary }, themeStore.getMainTextStyle]}
                    autoCapitalize={'none'}
                    placeholder={I18n.translation.AddComment + '...'}
                    placeholderTextColor={themeStore.theme.contrastTextColor}
                    selectionColor={themeStore.theme.primary}
                    blurOnSubmit={false}
                    underlineColorAndroid={'transparent'}
                    multiline={true}
                    autoCorrect={false}
                    onChangeText={onTextChanged}
                >{formattedAnswer}
                </TextInput>

            </KeyboardAwareScrollView>
            <Animatable.View transition={'bottom'} style={[{
                bottom: keyboard.keyboardShown ? keyboard.keyboardHeight : 0
            }]}>

                <PixelScaleButton style={[styles.centeredRow, styles.padding]}>
                    <Image source={require('../../Assets/Images/Icons/icAddImage.png')} />
                    <PixelwolfText style={[styles.smallMarginLeft]} size={'b17'} weight={'bold'} color={themeStore.theme.primary}>
                        {I18n.translation.AddImage}
                    </PixelwolfText>
                </PixelScaleButton>
            </Animatable.View>

        </Modal>
    );
}

export default forwardRef(AnswerModal)
