import { useCallback, useState } from "react";
import { useDispatch } from "react-redux";

import styles from "@/components/administrator/PostEditor/posteditor.module.css";

import Uploadbox from "@/components/administrator/form/UploadBox/upload.box";
import Input from "@/components/administrator/form/Input/input";
import Gallery from "@/components/administrator/Gallery/gallery";
import Editor from "@/components/editor/Editor";

import {
  addMiniWindow,
  removeAllMiniWindow,
} from "@/utils/store/features/ui/miniwindow.slice";

import { filterEmptyTag, objecthasKey } from "@/app/library/library";
// import { useEditor } from "@/components/editor/hooks/useEditor";
import useGalleryManagement from "@/hooks/useGalleryManagement";
import { useEditorPlugin } from "../../EditorMD/hooks/useEditorPlugin";
import EditorMD from "../../EditorMD/editor.markdown";

const Content = ({ data, setData, media, setMedia, save }) => {
  const dispatch = useDispatch();
  // const { editor: suneditor, insertHtml, setContents } = useEditor();

  const { galleryPlugin, uploadPlugin } = useEditorPlugin();

  const [isFromUpload, setIsFromUpload] = useState(false);
  const { gallery } = useGalleryManagement();

  const setImage = useCallback(
    (file, uid) => {
      // set alt text from gallery data
      if (objecthasKey(file, "alt"))
        setData((prev) => ({
          ...prev,
          media: { ...prev.media, alt: file.alt },
        }));

      // file.id => from gallery manager
      // file.files[0].id => from file input
      const media = file?._id || file?.files?.[0]?._id;
      setMedia((prev) => ({ ...prev, [uid]: file }));
      setTimeout(() => {
        setData((prev) => ({ ...prev, media: { ...prev.media, _id: media } }));
      });
    },
    [setData, setMedia]
  );

  const removeImage = useCallback(() => {
    setMedia((prev) =>
      Object.fromEntries(
        Object.entries(prev).filter(([k, _]) => k !== "thumbnail")
      )
    );
    setIsFromUpload(false);
    setTimeout(() => {
      setData((prev) => ({
        ...prev,
        media: {
          ...prev.media,
          _id: null,
          alt: "",
        },
      }));
    });
  }, [setData, setMedia]);

  return (
    <>
      <Uploadbox
        callback={setImage}
        onCancel={removeImage}
        label="Image Thumbnail"
        uid="thumbnail"
        currentImage={media["thumbnail"] || null}
        getIsUploaded={(isUploaded) => setIsFromUpload(isUploaded)}
      />
      {data.media && (
        <Input
          label="Alt"
          className={styles.input}
          value={data.media.alt || ""}
          labelclassname={styles.label}
          disabled={!isFromUpload}
          onChange={(e) =>
            setData((prev) => ({
              ...prev,
              media: { ...prev.media, alt: e.target.value },
            }))
          }
        />
      )}
      <div className={styles.content}>
        <div className={styles.content_header}>
          <p>Content</p>
          <span
            onClick={async () => {
              await gallery({
                page: 1,
                limit: 50,
                onSuccess: (galleries) => {
                  dispatch(
                    addMiniWindow({
                      status: true,
                      component: Gallery,
                      initialData: galleries,
                      onSelected: async (result) => {
                        const imageTag = `<img src="${result?._url}" alt="${result?.alt}" />`;
                        insertHtml(imageTag);
                        dispatch(removeAllMiniWindow());
                      },
                    })
                  );
                },
                onLoaded: () => {},
              });
            }}>
            Add Media
          </span>
        </div>
        {/* <Editor
          content={data?.content || ""}
          onChange={(content) => {
            const filteredContent = filterEmptyTag(content);
            // setContents(filteredContent);
            setData((prev) => ({ ...prev, content: filteredContent }));
          }}
          placeholder="Write the content here..."
          contentStyle="font-family: Inter;"
          callBackSave={() => {
            save();
            return false;
          }} // prevent default save
        /> */}

        <EditorMD
          data={data?.content || ""}
          onChange={(data) => {
            console.log({ datafromeditor: data });
            setData((prev) => ({ ...prev, content: data }));
          }}
          config={{
            tools: {
              gallery: {
                status: true,
                trigger: galleryPlugin,
              },
              image: {
                status: true,
                upload: uploadPlugin,
              },
            },
          }}
        />
      </div>
    </>
  );
};

export default Content;
