import dynamic from "next/dynamic";
import { useEffect, useRef, useState } from "react";
import "react-quill/dist/quill.snow.css";
import * as yup from "yup";

// Carrega o Quill dinamicamente sem SSR
const ReactQuill = dynamic(
  async () => {
    const { default: RQ } = await import("react-quill");
    return function comp({ forwardedRef, ...props }: any) {
      return <RQ ref={forwardedRef} {...props} />;
    };
  },
  { ssr: false, loading: () => <p>Loading editor...</p> }
);

interface EditorQuillProps {
  label?: string;
  labelSize?: string;
  value?: string;
  onChange?: (content: string) => void;
  readOnly?: boolean;
  modules?: object;
  className?: string;
  formulario?: any;
  name?: string;
  error?: string;
  required?: boolean;
  defaultValue?: string;
}

interface QuillModules {
  toolbar: (string | {})[][];
}

const EditorQuill: React.FC<EditorQuillProps> = ({
  label,
  labelSize = "text-md",
  value,
  onChange = () => {},
  readOnly = false,
  className = "",
  formulario,
  name = "",
  error,
  required = false,
  defaultValue,
}) => {
  const [isClient, setIsClient] = useState(false);
  const [quillRef, setQuillRef] = useState<any>(null);
  const reactQuillRef = useRef<any>(null);

  const [modules, setModules] = useState<QuillModules>({
    toolbar: [
      [{ font: [] }],
      [{ size: [] }],
      ["bold", "italic", "underline", "strike"],
      [{ color: [] }], // Adiciona o seletor de cores
      [{ list: "ordered" }, { list: "bullet" }],
      [{ align: [] }],
      ["link"],
      ["clean"],
    ],
  });

  useEffect(() => {
    if (typeof window !== "undefined") {
      const Quill = require("quill");
      const Font = Quill.import("formats/font");
      const Size = Quill.import("formats/size");

      Font.whitelist = ["arial", "helvetica", "times-new-roman", "courier-new"];
      Size.whitelist = [
        // "8px",
        // "10px",
        "12px",
        "14px",
        "16px",
        "18px",
        "20px",
        "24px",
        // "32px",
        // "48px",
      ];

      Quill.register(Font, true);
      Quill.register(Size, true);

      setModules({
        toolbar: [
          [{ font: Font.whitelist }],
          [{ size: Size.whitelist }],
          ["bold", "italic", "underline", "strike"],
          [
            {
              color: [
                "#000000",
                "#e60000",
                "#ff9900",
                "#ffff00",
                "#008a00",
                "#0066cc",
                "#9933ff",
                "#ffffff",
                "#facccc",
                "#ffebcc",
                "#ffffcc",
                "#cce8cc",
                "#cce0f5",
                "#ebd6ff",
                "#bbbbbb",
                "#f06666",
                "#ffc266",
                "#ffff66",
                "#66b966",
                "#66a3e0",
                "#c285ff",
                "#888888",
                "#a10000",
                "#b26b00",
                "#b2b200",
                "#006100",
                "#0047b2",
                "#6b24b2",
                "#444444",
                "#5c0000",
                "#663d00",
                "#666600",
                "#003700",
                "#002966",
                "#3d1466",
              ],
            },
          ],
          [{ list: "ordered" }, { list: "bullet" }],
          [{ align: [] }],
          ["link"],
          ["clean"],
        ],
      });
    }
  }, []);

  useEffect(() => {
    if (formulario && name) {
      const newSchema = formulario.yupSchema.fields;
      newSchema[name] = required ? yup.string().required(error) : yup.string();
      formulario.setYupSchema(yup.object().shape(newSchema));

      if (
        defaultValue &&
        (!Object.keys(formulario?.control?._formValues).includes(name) ||
          formulario?.control?._formValues[name] === undefined ||
          formulario?.control?._formValues[name] === "")
      ) {
        formulario.setValue(name, defaultValue);
      }
    }

    setIsClient(true);
  }, []);

  useEffect(() => {
    attachQuillRefs();
  });

  const attachQuillRefs = () => {
    if (typeof reactQuillRef.current?.getEditor !== "function") return;
    setQuillRef(reactQuillRef.current.getEditor());
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    const value = e.dataTransfer.getData("text/plain");

    if (quillRef) {
      const range = quillRef.getSelection();
      const position = range ? range.index : 0;
      quillRef.insertText(position, value);
    }
  };

  if (!isClient) return null;

  return (
    <div className="w-full">
      {label && (
        <label
          htmlFor={name}
          className={`mb-2.5 block text-black dark:text-white whitespace-nowrap ${labelSize}`}
        >
          {label
            .split(" ")
            .map((str: string) =>
              str.length > 3 ? str[0].toUpperCase() + str.slice(1) : str
            )
            .join(" ")}{" "}
          <span className="text-[#ff2b2b] font-semibold text-lg">
            {required && "*"}
          </span>
        </label>
      )}
      <div onDrop={handleDrop} onDragOver={(e) => e.preventDefault()}>
        <ReactQuill
          forwardedRef={(el: any) => {
            reactQuillRef.current = el;
          }}
          className={className}
          value={formulario ? formulario.watch(name) : value}
          onChange={(content: string) => {
            if (formulario) {
              formulario.setValue(name, content);
            }
            onChange(content);
          }}
          readOnly={readOnly}
          modules={modules}
        />
      </div>
      {formulario?.errors &&
        name &&
        formulario.errors[name] &&
        formulario.errors[name].message && (
          <span className="text-danger text-sm">
            {formulario.errors[name].message}
          </span>
        )}
    </div>
  );
};

export default EditorQuill;
