"use client";

import { Button, ButtonGroup, Grid, IconButton, ToggleButton, ToggleButtonGroup } from "@mui/material";
import "./MailField.css"
import { useEditor, EditorContent, Editor } from "@tiptap/react"
import FormatBoldIcon from '@mui/icons-material/FormatBold';
import React, { useCallback } from "react";
import { FormatItalic, FormatUnderlined } from "@mui/icons-material";
import { MuiColorInput, MuiColorInputColors, MuiColorInputValue } from 'mui-color-input'
import BorderColorIcon from '@mui/icons-material/BorderColor';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import FormatColorTextIcon from '@mui/icons-material/FormatColorText';
import FormatAlignLeftIcon from '@mui/icons-material/FormatAlignLeft';
import FormatAlignJustifyIcon from '@mui/icons-material/FormatAlignJustify';
import FormatAlignRightIcon from '@mui/icons-material/FormatAlignRight';

interface Props {
    editor: Editor | null;
}

const colorInputSx = {
    width: 150,
    height: 25,
    ".MuiInputBase-colorPrimary": {
        margin: -1,
        borderRadius: "0px 5px 5px 0px",
        borderColor: "rgba(0, 0, 0, 0)",
        backgroundColor: "rgba(0, 0, 0, 0)",
    },
    ".Mui-focused": {
        borderColor: "rgba(0, 0, 0, 0)",
    },
    ".MuiColorInput-Button": {
        marginBottom: 2,
        borderColor: "rgba(0, 0, 0, 0)",
        backgroundColor: "rgba(0, 0, 0, 0)",
    },
    ".MuiInputBase-input": {
        marginBottom: 1.5,
    },
}

const fontFamily = [
    {
        label: 'Arial',
        value: 'Arial',
    },
    {
        label: 'Times New Roman',
        value: 'Times New Roman',
    },
    {
        label: 'Courier New',
        value: 'Courier New',
    },
    {
        label: 'Georgia',
        value: 'Georgia',
    },
    {
        
    }
]

const MailToolbar: React.FC<Props> = ({
    editor
}) => {

    if (editor == null) {
        return null
    }

    const [fontStyle, setFontStyle] = React.useState<string[]>(() => ["alignLeft"]);
    const [colorHighlightValue, setColorHighlightValue] = React.useState<MuiColorInputValue>("red");
    const [colorTextValue, setColorTextValue] = React.useState<MuiColorInputValue>("black");
    const colorHighlightValueInputRef = React.useRef<any>(null);
    const colorTextValueInputRef = React.useRef<any>(null);

    const handleFontStyle = useCallback((
        event: React.MouseEvent<HTMLElement>,
        newFontStyles: string[],
    ) => {

        setFontStyle((prev) => {
            const id = event.currentTarget?.id
            const include = prev.includes(id)

            if (include) {
                return prev.filter(ele => ele !== id)
            } else {
                prev = prev.filter(ele => !ele.includes("align"))
                prev.push(id)
                return prev
            }
        });
    }, []);

    const handleColorHighlightValue = useCallback((value: string, colors: MuiColorInputColors) => {
        // console.log(colors)
        setColorHighlightValue(() => value)
        // editor.chain().focus().toggleHighlight({ color: value }).run()
    }, [])

    const handleColorHighlightValueClick = useCallback((event: React.MouseEvent<HTMLElement>) => {
        editor.chain().focus().toggleHighlight({ color: colorHighlightValue.toString() }).run()
    }, [colorHighlightValue])

    const handleColorHighlightValueClose = useCallback((event: {}, reason: "backdropClick" | "escapeKeyDown") => {
        // console.log(event)
        editor.chain().focus().toggleHighlight({ color: colorHighlightValue.toString() }).run()
    }, [colorHighlightValue])

    const handleColorHighlightValueBlur = useCallback((event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        editor.chain().focus().toggleHighlight({ color: colorHighlightValue.toString() }).run()
    }, [colorHighlightValue])

    const handleColorTextValue = useCallback((value: string, colors: MuiColorInputColors) => {
        // console.log(colors)
        setColorTextValue(() => value)
        // if (editor.isActive("textStyle")) {
        //     editor.chain().focus().unsetColor().run()
        // } else {
        //     editor.chain().focus().setColor(value).run()
        // }
    }, [])

    const handleColorTextValueClick = useCallback((event: React.MouseEvent<HTMLElement>) => {
        if (editor.isActive("textStyle", { color: colorTextValue.toString() })) {
            editor.chain().focus().unsetColor().run()
        } else {
            editor.chain().focus().setColor(colorTextValue.toString()).run()
        }
    }, [colorTextValue])

    const handleColorTextValueClose = useCallback((event: {}, reason: "backdropClick" | "escapeKeyDown") => {
        if (editor.isActive("textStyle", { color: colorTextValue.toString() })) {
            editor.chain().focus().unsetColor().run()
        } else {
            editor.chain().focus().setColor(colorTextValue.toString()).run()
        }
    }, [colorTextValue])

    const handleColorTextValueBlur = useCallback((event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        if (editor.isActive("textStyle", { color: colorTextValue.toString() })) {
            editor.chain().focus().unsetColor().run()
        } else {
            editor.chain().focus().setColor(colorTextValue.toString()).run()
        }
    }, [colorTextValue])

    const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
        if (event.key === 'Enter') {
            if (colorHighlightValueInputRef.current !== null) {
                colorHighlightValueInputRef.current.blur();
            }

            if (colorTextValueInputRef.current !== null) {
                colorTextValueInputRef.current.blur();
            }
        }
    }

    const handleTextAlign = useCallback((event: React.MouseEvent<HTMLElement, MouseEvent>, value: any) => {
        console.log(value)
        switch (value) {
            case "alignLeft":
                if (editor.isActive({ textAlign: 'left' })) {
                    editor.chain().focus().unsetTextAlign().run()
                } else {
                    editor.chain().focus().setTextAlign('left').run()
                }
                break;
            case "alignCenter":
                if (editor.isActive({ textAlign: 'center' })) {
                    editor.chain().focus().unsetTextAlign().run()
                } else {
                    editor.chain().focus().setTextAlign('center').run()
                }
                break;
            case "alignRight":
                if (editor.isActive({ textAlign: 'right' })) {
                    editor.chain().focus().unsetTextAlign().run()
                } else {
                    editor.chain().focus().setTextAlign('right').run()
                }
                break;
            default:
                break;
        }
    }, [])

    React.useEffect(() => {
        editor.on('selectionUpdate', ({ editor }) => {
            const currentFormatList: string[] = []
            if (editor.isActive("bold")) {
                currentFormatList.push("bold")
            }

            if (editor.isActive("italic")) {
                currentFormatList.push("italic")
            }

            if (editor.isActive("underline")) {
                currentFormatList.push("underline")
            }

            if (editor.isActive("highlight", { color: colorHighlightValue.toString() })) {
                currentFormatList.push("highlight")
            }

            if (editor.isActive("textStyle", { color: colorTextValue.toString() })) {
                currentFormatList.push("textStyle")
            }

            if (editor.isActive({ textAlign: 'left' })) {
                currentFormatList.push("alignLeft")
            }

            if (editor.isActive({ textAlign: 'center' })) {
                currentFormatList.push("alignCenter")
            }

            if (editor.isActive({ textAlign: 'right' })) {
                currentFormatList.push("alignRight")
            }

            console.log(currentFormatList)
            setFontStyle(() => currentFormatList)
        })
    }, [editor])

    return (
        <Grid container>
            <ToggleButtonGroup
                value={fontStyle}
                onChange={handleFontStyle}
            >
                <ToggleButton id="bold" value="bold" onClick={() => editor.chain().focus().toggleBold().run()}>
                    <FormatBoldIcon />
                </ToggleButton>
                <ToggleButton id="italic" value="italic" onClick={() => editor.chain().focus().toggleItalic().run()}>
                    <FormatItalic />
                </ToggleButton>
                <ToggleButton id="underline" value="underline" onClick={() => editor.chain().focus().toggleUnderline().run()}>
                    <FormatUnderlined />
                </ToggleButton>
            </ToggleButtonGroup>

            <ToggleButtonGroup
                value={fontStyle}
                onChange={handleFontStyle}
                sx={{ marginLeft: 2 }}
            >
                <ToggleButton id="highlight" value="highlight" onClick={handleColorHighlightValueClick}>
                    <BorderColorIcon sx={{ color: colorHighlightValue as string }} />
                </ToggleButton>
                {/* <ToggleButton value="" onClick={() => console.log("Expand more")}>
                    <ExpandMoreIcon sx={{ width: 15 }} fontSize="large"/>
                </ToggleButton> */}
                <ToggleButton id="highlight" value="highlight">
                    <MuiColorInput
                        sx={colorInputSx}
                        format="hex8"
                        value={colorHighlightValue}
                        onBlur={handleColorHighlightValueBlur}
                        onChange={handleColorHighlightValue}
                        onKeyDown={handleKeyDown}
                        inputRef={colorHighlightValueInputRef}
                        PopoverProps={{
                            onClose: handleColorHighlightValueClose
                        }}
                    />
                </ToggleButton>
            </ToggleButtonGroup>

            <ToggleButtonGroup
                value={fontStyle}
                onChange={handleFontStyle}
                sx={{ marginLeft: 2 }}
            >
                <ToggleButton id="textStyle" value="textStyle" onClick={handleColorTextValueClick}>
                    <FormatColorTextIcon sx={{ color: colorTextValue as string }} />
                </ToggleButton>
                <ToggleButton id="textStyle" value="textStyle">
                    <MuiColorInput
                        sx={colorInputSx}
                        format="hex8"
                        value={colorTextValue}
                        onBlur={handleColorTextValueBlur}
                        onChange={handleColorTextValue}
                        onKeyDown={handleKeyDown}
                        inputRef={colorTextValueInputRef}
                        PopoverProps={{
                            onClose: handleColorTextValueClose
                        }}
                    />
                </ToggleButton>
            </ToggleButtonGroup>

            <ToggleButtonGroup
                value={fontStyle}
                onChange={handleFontStyle}
                sx={{ marginLeft: 2 }}
            >
                <ToggleButton id="alignLeft" value="alignLeft" onClick={handleTextAlign}>
                    <FormatAlignLeftIcon />
                </ToggleButton>
                <ToggleButton id="alignCenter" value="alignCenter" onClick={handleTextAlign}>
                    <FormatAlignJustifyIcon />
                </ToggleButton>
                <ToggleButton id="alignRight" value="alignRight" onClick={handleTextAlign}>
                    <FormatAlignRightIcon />
                </ToggleButton>
            </ToggleButtonGroup>
        </Grid>
    );
};

export default MailToolbar;