// import EditorMenu from '@/components/EditorMenu';
import { format } from 'date-fns';
// import { useRouter } from 'expo-router';
// import React, { useEffect, useState } from 'react';
// import { Keyboard, ScrollView, StyleSheet, TextInput } from 'react-native';
import { Appbar, useTheme } from 'react-native-paper';
// import { useSafeAreaInsets } from 'react-native-safe-area-context';
// import { EditorContent, useEditor } 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 editor = useEditor({
//         enableCoreExtensions: true,
//         onUpdate(props) {
//             const newText = props.editor.getNativeText();
//             // setEntryText(newText);
//         },
//     });



//     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}
//                 style={{
//                     paddingHorizontal: 15,
//                 }}
//                 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 + 10,
//                     left: 10,
//                     right: 0,
//                     flexDirection: 'row',
//                 }}>
//                 <EditorMenu editor={editor} />

//                 {/* <View
//                     pointerEvents='box-none'
//                     style={{
//                         borderColor: theme.colors.primary,
//                         borderWidth: 1,
//                         borderRadius: 24,
//                         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,
//     },
// });

import Wrapper from '@/components/ui/Wrapper';
import { CoreBridge, RichText, TenTapStartKit, Toolbar, useEditorBridge, useEditorContent } from '@10play/tentap-editor';
import { useRouter } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { Keyboard, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

export default function NewEntryScreen() {
    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 });
        console.log('Entry text updated:', entryText);
    }
        , [entryText]);

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

    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();
        };
    }, []);

    const editor = useEditorBridge({
        autofocus: true,
        avoidIosKeyboard: true,
        theme: {
            webviewContainer: {
                paddingLeft: 15,
                backgroundColor: theme.colors.surface,
            },
        },
        bridgeExtensions: [
            ...TenTapStartKit,
            CoreBridge.configureCSS(`
                * {
                    font-size: 12px;
                }
                `), // Custom font
        ],
    });
    const content = {
        html: useEditorContent(editor, { type: 'html' }),
        text: useEditorContent(editor, { type: 'text' }),
    };
    useEffect(() => {
        content && setEntryText(content.text ?? '');
    }, [content]);

    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>

            {/* <SafeAreaView style={{ flex: 1, backgroundColor: theme.colors.background }}> */}
            <RichText editor={editor} />
            <View
                // horizontal={true}
                // keyboardShouldPersistTaps="always"
                style={{
                    position: 'absolute',
                    bottom: keyboardHeight + insets.bottom,
                    left: 10,
                    right: 0,
                    flexDirection: 'row',
                }}>
                <Toolbar editor={editor} hidden={false} />
            </View>
            {/* </SafeAreaView> */}

        </Wrapper>
    );
};