import { useCallback } from "react";

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

import Input from "@/components/administrator/form/Input/input";
import Uploadbox from "@/components/administrator/form/UploadBox/upload.box";
import TextArea from "@/components/administrator/form/TextArea/text.area";

const SEO = ({ data, setData, media, setMedia }) => {
  const setImage = useCallback(
    (file, uid) => {
      // 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,
          metadata: {
            ...prev.metadata,
            image: media,
          },
        }));
      });
    },
    [setData, setMedia]
  );

  const removeImage = useCallback(() => {
    setMedia((prev) =>
      Object.fromEntries(
        Object.entries(prev).filter(([k, _]) => k !== "meta-image")
      )
    );
    setTimeout(() => {
      setData((prev) => ({
        ...prev,
        metadata: { ...prev.metadata, image: null },
      }));
    });
  }, [setData, setMedia]);

  return (
    <>
      <Input
        label="Title"
        required={true}
        className={styles.input}
        value={data?.metadata?.title || ""}
        labelclassname={styles.label}
        onChange={(e) =>
          setData((prev) => ({
            ...prev,
            metadata: { ...prev.metadata, title: e.target.value },
          }))
        }
        format={{
          label: "Set Some as Post Title",
          changeInput: true,
          action: (element) => {
            setData((prev) => ({
              ...prev,
              metadata: { ...prev.metadata, title: data?.title || "" },
            }));
            return data?.title || "";
          },
        }}
      />
      <Uploadbox
        callback={setImage}
        onCancel={removeImage}
        label="Meta Image"
        uid="meta-image"
        currentImage={media["meta-image"] || null}
      />
      <TextArea
        label="Description"
        className={styles.input}
        labelclassname={styles.label}
        value={data?.metadata?.description || ""}
        onChange={(e) =>
          setData((prev) => ({
            ...prev,
            metadata: { ...prev.metadata, description: e.target.value },
          }))
        }
      />
    </>
  );
};

export default SEO;
