"use client";

import "./MailField.css"
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import Underline from '@tiptap/extension-underline'
import { useEditor, EditorContent, Extension } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import MailToolbar from "./MailToolbar";
import { Grid } from "@mui/material";
import Highlight from '@tiptap/extension-highlight'
import { Color } from '@tiptap/extension-color'
import ListItem from "@tiptap/extension-list-item";
import TextStyle from "@tiptap/extension-text-style";
import TextAlign from '@tiptap/extension-text-align'

interface Props {
    content?: string,
    onChange?: (richText: string) => void,
    error?: boolean,
}

const MailField: React.FC<Props> = ({
    content,
    onChange,
    error
}) => {

    const TAB_CHAR = '\u0009';

    const TabHandler = Extension.create({
        name: 'tabHandler',
        addKeyboardShortcuts() {
            return {
                Tab: ({ editor }) => {
                    // Sinks a list item / inserts a tab character
                    editor
                        .chain()
                        .sinkListItem('listItem')
                        .command(({ tr }) => {
                            tr.insertText(TAB_CHAR);
                            return true;
                        })
                        .run();
                    // Prevent default behavior (losing focus)
                    return true;
                },
            };
        },
    });

    const editor = useEditor({
        extensions: [
            StarterKit.configure(),
            Document,
            Paragraph,
            Text,
            TextStyle,
            TextAlign.configure({
                types: ['heading', 'paragraph']
            }),
            Underline,
            Highlight.configure({ multicolor: true }),
            Color,
            ListItem,
            TabHandler
        ],
        content: content,
        onUpdate({ editor }) {
            if (onChange) {
                onChange(editor.getHTML())
            }
            console.log(editor.getHTML())
        },
    })

    return (
        <Grid container rowSpacing={1}>
            <Grid item xs={12}>
                <MailToolbar editor={editor} />
            </Grid>
            <Grid item xs={12} >
                <EditorContent className={error === true ? "tiptap-error" : ""} label="Template" editor={editor}/>
            </Grid>
        </Grid>
    );
};

export default MailField;