import React, { useEffect, useRef, useState } from 'react';
import { StyleSheet, ScrollView, View, TextInput, KeyboardAvoidingView, Platform, Keyboard } from 'react-native';
import { Button, Text, useTheme, Appbar, IconButton, Chip, Surface } from 'react-native-paper';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { useRouter } from 'expo-router';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { StatusBar } from 'expo-status-bar';
import Wrapper from '@/components/ui/Wrapper';
import { format } from 'date-fns';
import { useEditor, EditorContent } from 'rn-text-editor';

export default function NewEntryScreen() {
    const navigation = useRouter();
    const theme = useTheme();
    const entryDate = format(new Date(), 'LLL d, h:mm aaa');

    const [entryText, setEntryText] = useState<string>('');
    const [stats, setStats] = useState<{ words: number; characters: number }>({
        words: 0,
        characters: 0,
    });

    useEffect(() => {
        const words = entryText.trim().split(/\s+/).filter(Boolean).length;
        const characters = entryText.length;
        setStats({ words, characters });
    }
        , [entryText]);

    const inputRef = React.useRef<TextInput>(null) as React.RefObject<TextInput>;
    const editor = useEditor({
        enableCoreExtensions: true,
        onUpdate(props) {
            const newText = props.editor.getNativeText();
            setEntryText(newText);
        },    // Add these properties to improve compatibility

    });

    const insets = useSafeAreaInsets();
    const [keyboardHeight, setKeyboardHeight] = useState(0);
    useEffect(() => {
        const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
            setKeyboardHeight(Keyboard.metrics()?.height || 0);
        });
        const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
            setKeyboardHeight(0);
        });

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

    return (
        <Wrapper>
            <Appbar.Header style={{
                backgroundColor: theme.colors.primary,
                borderBottomWidth: 2,
                borderBottomColor: theme.colors.backdrop,
            }}>
                {
                    stats['characters'] === 0 ?
                        <Appbar.BackAction onPress={() => {
                            navigation.back();
                        }} />
                        :
                        <Appbar.Action icon="check" onPress={() => {
                            navigation.back();
                        }} />
                }
                <Appbar.Content title={entryDate}
                    titleStyle={{
                        fontSize: 16, fontWeight: 'bold',
                    }}
                />
                <Appbar.Action icon="calendar" onPress={() => { }} />
                <Appbar.Action icon="tag" onPress={() => { }} />
            </Appbar.Header>
            <Text
                style={{
                    fontSize: 10,
                    backgroundColor: theme.colors.accent,
                    color: theme.colors.onTertiary,
                    paddingVertical: 2,
                    textAlign: 'center',
                }}>
                {stats.words} words · {stats.characters} characters
            </Text>
            <EditorContent
                editor={editor}
                placeholder="Write something..."
                inputRef={inputRef}
                autoFocus
            />
            {/* 
            <TextInput
                ref={inputRef}
                style={{
                    flex: 1,
                    fontSize: 14,
                    color: theme.colors.onSurface,
                    backgroundColor: theme.colors.surface,
                    padding: 10,
                    textAlignVertical: 'top',
                }}
                cursorColor={theme.colors.primary}
                multiline
                autoFocus
                autoCapitalize='none'
                placeholder="Write your entry here..."
                value={entryText}
                onChangeText={setEntryText}
            /> */}
            <ScrollView
                horizontal={true}
                keyboardShouldPersistTaps="always"
                style={{
                    position: 'absolute',
                    bottom: keyboardHeight + insets.bottom,
                    left: 0,
                    right: 0,
                    flexDirection: 'row',
                }}>
                <View
                    pointerEvents='box-none'
                    style={{
                        borderColor: theme.colors.primary,
                        borderWidth: 1,
                        borderRadius: 24,
                        margin: 5,
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-around',
                        backgroundColor: theme.colors.surface,
                        shadowColor: '#000',
                        shadowOffset: {
                            width: 0,
                            height: 2,
                        },
                        shadowOpacity: 0.1,
                        shadowRadius: 8,
                        elevation: 4,
                    }}>
                    < IconButton
                        icon="format-bold"
                        size={24} accessible={false}

                        onPress={() => {
                            console.log('Bold button pressed'); inputRef.current?.focus();

                        }}
                    />
                    <IconButton
                        icon="format-italic"
                        size={24}
                        onPress={() => {
                            console.log('Italic button pressed');
                        }}
                    />
                    <IconButton
                        icon="format-underline"
                        size={24}
                        onPress={() => {
                            console.log('Underline button pressed');
                        }}
                    />
                </View>
            </ScrollView>
        </Wrapper >
    );
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        paddingHorizontal: 1,
    },
    editorContainer: {
        paddingHorizontal: 5,
        flex: 1
    },
    box: {
        width: 60,
        height: 60,
        marginVertical: 20,
    },
});