"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";
import { useTranslation } from "react-i18next";
import GridOnIcon from "@mui/icons-material/GridOn";

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 }) => {
  const { t } = useTranslation();
  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;
      }
    },
    [],
  );

  const handleInsertTable = useCallback(() => {
    editor
      .chain()
      .focus()
      .insertTable({ rows: 3, cols: 3, withHeaderRow: true })
      .run();
  }, []);

  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>

      <ToggleButtonGroup sx={{ marginTop: 2 }}>
        <ToggleButton
          id="insertTable"
          value="insertTable"
          onClick={() =>
            editor
              .chain()
              .focus()
              .insertTable({ rows: 3, cols: 3, withHeaderRow: true })
              .run()
          }
        >
          <GridOnIcon />
          {t("Insert Table")}
        </ToggleButton>
        <ToggleButton
          id="deleteTable"
          value="deleteTable"
          onClick={() => editor.chain().focus().deleteTable().run()}
        >
          {t("Delete table")}
        </ToggleButton>
        <ToggleButton
          id="addColumnBefore"
          value="addColumnBefore"
          onClick={() => editor.chain().focus().addColumnBefore().run()}
        >
          {t("Add column before")}
        </ToggleButton>
        <ToggleButton
          id="addColumnAfter"
          value="addColumnAfter"
          onClick={() => editor.chain().focus().addColumnAfter().run()}
        >
          {t("Add column after")}
        </ToggleButton>
        <ToggleButton
          id="deleteColumn"
          value="deleteColumn"
          onClick={() => editor.chain().focus().deleteColumn().run()}
        >
          {t("Delete column")}
        </ToggleButton>
        <ToggleButton
          id="addRowBefore"
          value="addRowBefore"
          onClick={() => editor.chain().focus().addRowBefore().run()}
        >
          {t("Add row before")}
        </ToggleButton>
        <ToggleButton
          id="addRowAfter"
          value="addRowAfter"
          onClick={() => editor.chain().focus().addRowAfter().run()}
        >
          {t("Add row after")}
        </ToggleButton>
        <ToggleButton
          id="deleteRow"
          value="deleteRow"
          onClick={() => editor.chain().focus().deleteRow().run()}
        >
          {t("Delete row")}
        </ToggleButton>
        <ToggleButton
          id="mergeCells"
          value="mergeCells"
          onClick={() => editor.chain().focus().mergeCells().run()}
        >
          {t("Merge cells")}
        </ToggleButton>
        <ToggleButton
          id="splitCell"
          value="splitCell"
          onClick={() => editor.chain().focus().splitCell().run()}
        >
          {t("Split cell")}
        </ToggleButton>
      </ToggleButtonGroup>
      <ToggleButtonGroup
      // sx={{ marginLeft: 2 }}
      >
        <ToggleButton
          id="toggleHeaderColumn"
          value="toggleHeaderColumn"
          onClick={() => editor.chain().focus().toggleHeaderColumn().run()}
        >
          {t("Toggle header column")}
        </ToggleButton>
        <ToggleButton
          id="toggleHeaderRow"
          value="toggleHeaderRow"
          onClick={() => editor.chain().focus().toggleHeaderRow().run()}
        >
          {t("Toggle header row")}
        </ToggleButton>
        <ToggleButton
          id="toggleHeaderCell"
          value="toggleHeaderCell"
          onClick={() => editor.chain().focus().toggleHeaderCell().run()}
        >
          {t("Toggle header cell")}
        </ToggleButton>
        <ToggleButton
          id="mergeOrSplit"
          value="mergeOrSplit"
          onClick={() => editor.chain().focus().mergeOrSplit().run()}
        >
          {t("Merge or split")}
        </ToggleButton>
        <ToggleButton
          id="setCellAttribute"
          value="setCellAttribute"
          onClick={() =>
            editor.chain().focus().setCellAttribute("colspan", 2).run()
          }
        >
          {t("Set cell attribute")}
        </ToggleButton>
        <ToggleButton
          id="fixTables"
          value="fixTables"
          onClick={() => editor.chain().focus().fixTables().run()}
        >
          {t("Fix tables")}
        </ToggleButton>
        <ToggleButton
          id="goToNextCell"
          value="goToNextCell"
          onClick={() => editor.chain().focus().goToNextCell().run()}
        >
          {t("Go to next cell")}
        </ToggleButton>
        <ToggleButton
          id="goToPreviousCell"
          value="goToPreviousCell"
          onClick={() => editor.chain().focus().goToPreviousCell().run()}
        >
          {t("Go to previous cell")}
        </ToggleButton>
      </ToggleButtonGroup>
    </Grid>
  );
};

export default MailToolbar;
