"use client";

import { useEffect, useState } from "react";
import { toast } from "sonner";
import { useEditor, EditorContent,} from "@tiptap/react";

import StarterKit from "@tiptap/starter-kit";
import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";

import {
  FaBold,
  FaItalic,
  FaListUl,
  FaListOl,
  FaUndo,
  FaRedo,
  FaLink,
  FaImage,
  FaQuoteRight,
  FaMinus,
  FaCode,
} from "react-icons/fa";

import { uploadBlogImage } from "@/services/upload";

interface Props {
  value: string;
  onChange: (html: string) => void;
}

export default function BlogEditor({
  value,
  onChange,
}: Props) {
  const [uploadingImage, setUploadingImage] =
  useState(false);
  const editor = useEditor({
    extensions: [
      StarterKit,
      Image,
      Placeholder.configure({
        placeholder: "Start writing your blog...",
      }),
    ],

    content: value,

    immediatelyRender: false,

    onUpdate({ editor }) {
      onChange(editor.getHTML());
    },
  });

  useEffect(() => {
    if (!editor) return;

    if (editor.getHTML() !== value) {
      editor.commands.setContent(value, {
        emitUpdate: false,
      });
    }
  }, [editor, value]);

  if (!editor) return null;

  return (
    <div className="overflow-hidden rounded-2xl border">

      {/* Toolbar */}

      <div className="flex flex-wrap gap-2 border-b bg-stone-100 p-3">

        {/* Bold */}

        <button
          type="button"
          disabled={
            !editor.can().chain().focus().toggleBold().run()
          }
          onClick={() =>
            editor.chain().focus().toggleBold().run()
          }
          className={`rounded-lg p-2 transition ${
            editor.isActive("bold")
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          <FaBold />
        </button>

        {/* Italic */}

        <button
          type="button"
          disabled={
            !editor.can().chain().focus().toggleItalic().run()
          }
          onClick={() =>
            editor.chain().focus().toggleItalic().run()
          }
          className={`rounded-lg p-2 transition ${
            editor.isActive("italic")
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          <FaItalic />
        </button>

        {/* Heading */}

        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .toggleHeading({
                level: 1,
              })
              .run()
          }
          className={`rounded-lg px-3 py-2 transition ${
            editor.isActive("heading", {
              level: 1,
            })
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          H1
        </button>

        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .toggleHeading({
                level: 2,
              })
              .run()
          }
          className={`rounded-lg px-3 py-2 transition ${
            editor.isActive("heading", {
              level: 2,
            })
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          H2
        </button>

        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .toggleHeading({
                level: 3,
              })
              .run()
          }
          className={`rounded-lg px-3 py-2 transition ${
            editor.isActive("heading", {
              level: 3,
            })
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          H3
        </button>

        {/* Bullet List */}

        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .toggleBulletList()
              .run()
          }
          className={`rounded-lg p-2 transition ${
            editor.isActive("bulletList")
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          <FaListUl />
        </button>

        {/* Ordered List */}

        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .toggleOrderedList()
              .run()
          }
          className={`rounded-lg p-2 transition ${
            editor.isActive("orderedList")
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          <FaListOl />
        </button>

        {/* Blockquote */}
        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .toggleBlockquote()
              .run()
          }
          className={`rounded-lg p-2 transition ${
            editor.isActive("blockquote")
              ? "bg-[#C9A227] text-white"
              : "bg-white hover:bg-stone-200"
          }`}
        >
          <FaQuoteRight />
        </button>

       {/* Horizontal Rule */}
        <button
          type="button"
          onClick={() =>
            editor
              .chain()
              .focus()
              .setHorizontalRule()
              .run()
          }
          className="rounded-lg p-2 bg-white hover:bg-stone-200"
        >
          <FaMinus />
        </button>

        {/* Link */}

        <button
          type="button"
          onClick={() => {
            const url = prompt("Enter URL");

            if (!url) return;

            editor
              .chain()
              .focus()
              .setLink({
                href: url,
              })
              .run();
          }}
          className="rounded-lg bg-white p-2 transition hover:bg-stone-200"
        >
          <FaLink />
        </button>

        {/* Upload Image */}

        <button
          type="button"
          disabled={uploadingImage}
          className={`rounded-lg p-2 transition ${
            uploadingImage
              ? "bg-stone-300 cursor-not-allowed"
              : "bg-white hover:bg-stone-200"
          }`}
          onClick={async () => {
            const input =
              document.createElement("input");

            input.type = "file";
            input.accept = "image/*";

            input.click();

            input.onchange = async () => {
              if (!input.files?.length) return;

              try {
                setUploadingImage(true);

                const image =
                  await uploadBlogImage(
                    input.files[0]
                  );

                editor
                  .chain()
                  .focus()
                  .setImage({
                    src: image,
                  })
                  .run();

                toast.success(
                  "Image uploaded successfully."
                );

              } catch {

                toast.error(
                  "Image upload failed."
                );

              } finally {

                setUploadingImage(false);

              }
            };
          }}
        >
          {uploadingImage
            ? "..."
            : <FaImage />}
        </button>

        {/* Undo */}

        <button
          type="button"
          onClick={() => editor.commands.undo()}
          className="rounded-lg bg-white p-2 transition hover:bg-stone-200"
        >
          <FaUndo />
        </button>

        {/* Redo */}

        <button
          type="button"
          onClick={() => editor.commands.redo()}
          className="rounded-lg bg-white p-2 transition hover:bg-stone-200"
        >
          <FaRedo />
        </button>

      </div>

      {/* Editor */}

      <div className="blog-editor-content">
        <EditorContent editor={editor} />
      </div>

    </div>
  );
}