"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";

import styles from "@/components/administrator/TagEditor/tageditor.module.css";
import Input from "@/components/administrator/form/Input/input";
import TextArea from "@/components/administrator/form/TextArea/text.area";
import { slugify } from "@/app/library/library";
import Button from "@/components/ui/Button/button";
import Loader from "@/components/web/Loader/loader";
import { useTerm } from "@/hooks/useTerm";
import { useRouter } from "next/navigation";

/**
 *
 * @type {React.FC <{
 *    data: object;
 * }>}
 * @returns
 */
const TagEditor = (props) => {
  const router = useRouter();
  const [data, setData] = useState(props.data);
  const [slugLock, setSlugLock] = useState(true);
  const [loading, setLoading] = useState({
    save: false,
    delete: false,
  });

  const { updateTag, deleteTag } = useTerm();

  const isChange = useMemo(() => {
    return JSON.stringify(data) !== JSON.stringify(props.data);
  }, [props.data, data]);

  const handleDelete = useCallback(() => {
    setLoading((prev) => ({ ...prev, delete: true }));
    deleteTag(
      data._id,
      () => {
        router.push("/dashboard/tags");
        setLoading((prev) => ({ ...prev, delete: false }));
      },
      () => {
        setLoading((prev) => ({ ...prev, delete: false }));
      }
    );
  }, [data, deleteTag, router]);

  const handleSave = useCallback(() => {
    updateTag(data, (result) => {
      setData(result);
      setLoading((prev) => ({ ...prev, save: false }));
    });
  }, [data, updateTag]);

  useEffect(() => {
    const handleKeyDown = (e) => {
      const keyDown = [
        {
          on: e.key === "s" && e.ctrlKey,
          call: async () => {
            e.preventDefault();
            handleSave();
          },
        },
        {
          on: e.key === "Delete" && e.shiftKey,
          call: async () => {
            e.preventDefault();
            handleDelete();
          },
        },
      ];

      return keyDown.find((key) => key.on)?.call();
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [handleSave, handleDelete]);

  return (
    <>
      <h1 className={styles.post_title}>{data.name || "Unnamed"}</h1>
      <div className={styles.container}>
        <div className={styles.editor_header}>
          <div className={styles.editor_status}>
            <p>
              ID : <span>{data._id}</span>
            </p>
            <p>
              Status : <span>{isChange ? "Changed" : "Unchanged"}</span>
            </p>
          </div>
          <div className={styles.editor_status}>
            <Button
              className={styles.button}
              disabled={!isChange || loading.save}
              onClick={() => handleSave()}>
              {loading.save && (
                <>
                  <Loader
                    size={20}
                    color={"#fff"}
                  />
                </>
              )}
              Save
            </Button>
            <Button
              className={styles.button}
              disabled={loading.delete}
              onClick={() => handleDelete()}>
              {loading.delete && (
                <>
                  <Loader
                    size={20}
                    color={"#fff"}
                  />
                </>
              )}
              Delete
            </Button>
          </div>
        </div>
        <div className={styles.editor_content}>
          <div className={`${styles.editor_body}`}>
            <div className={styles.editor_post}>
              <Input
                label="Name"
                className={styles.input}
                value={data.name || ""}
                labelclassname={styles.label}
                onChange={(e) =>
                  setData((prev) => ({
                    ...prev,
                    name: e.target.value,
                    ...(slugLock ? { slug: slugify(e.target.value) } : {}),
                  }))
                }
              />
              <Input
                label="Slug"
                className={styles.input}
                value={data.slug || ""}
                disabled={slugLock}
                labelclassname={styles.label}
                format={{
                  label: slugLock ? "Unlock" : "Lock",
                  action: (element) => {
                    setTimeout(() => element.focus(), 200);
                    setSlugLock((prev) => !prev);
                  },
                  changeInput: false,
                }}
                onChange={(e) =>
                  setData((prev) => ({ ...prev, slug: e.target.value }))
                }
              />
              <TextArea
                label="Description"
                className={styles.input}
                labelclassname={styles.label}
                onChange={(e) =>
                  setData((prev) => ({ ...prev, description: e.target.value }))
                }
              />
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default TagEditor;
