import dynamic from "next/dynamic";
import { useEffect, useRef } from "react";
import * as yup from "yup";

const JoditEditor = dynamic(() => import("jodit-react"), {
  ssr: false,
  loading: () => <p>Carregando editor...</p>,
});

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

const EditorJodit: React.FC<EditorJoditProps> = ({
  label,
  labelSize = "text-md",
  value,
  onChange = () => {},
  readOnly = false,
  className = "",
  formulario,
  name = "",
  error,
  required = false,
  defaultValue,
}) => {
  const editor = useRef(null);
  //   const [isClient, setIsClient] = useState(false);

  //   const config = {
  //     readonly: readOnly,
  //     height: 400,
  //     buttons: [
  //       "bold",
  //       "italic",
  //       "underline",
  //       "strikethrough",
  //       "|",
  //       "font",
  //       "fontsize",
  //       "brush",
  //       "|",
  //       "ul",
  //       "ol",
  //       "|",
  //       "align",
  //       "link",
  //       "|",
  //       "undo",
  //       "redo",
  //       "|",
  //       "source",
  //     ],
  //     fonts: ["Arial", "Helvetica", "Times New Roman", "Courier New"],
  //   };

  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);
  }, []);

  //   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}{" "}
          <span className="text-[#ff2b2b] font-semibold text-lg">
            {required && "*"}
          </span>
        </label>
      )}
      <JoditEditor
        ref={editor}
        value={formulario ? formulario.watch(name) : value}
        //  config={config}
        onBlur={(newContent) => {
          if (formulario) {
            formulario.setValue(name, newContent);
          }
          onChange(newContent);
        }}
      />
      {formulario?.errors?.[name]?.message && (
        <span className="text-danger text-sm">
          {formulario.errors[name].message}
        </span>
      )}
    </div>
  );
};

export default EditorJodit;
