import React, { useEffect, useRef, useState, useSyncExternalStore } from "react";
import PropTypes from "prop-types";
import { useIntl } from "react-intl";
import { Field, Typography } from "@strapi/design-system";
import CKEReact from "./CKEReact";
import MediaLib from "./MediaLib.jsx";
import AIPanel from "./AIPanel.jsx";
import EditorGlobalStyles from "./EditorGlobalStyles.jsx";
import { getPresetsVersion, loadPresets, resolvePreset, subscribePresets } from "../presets";

const CKStudioField = ({
  name,
  value,
  onChange,
  attribute,
  error,
  required,
  disabled,
  hint,
  labelAction,
  intlLabel,
  label,
}) => {
  const { formatMessage } = useIntl();
  const presetsVersion = useSyncExternalStore(subscribePresets, getPresetsVersion);
  const preset = resolvePreset(attribute?.options?.preset);

  useEffect(() => {
    loadPresets();
  }, []);
  const editorRef = useRef(null);
  const [isMediaLibOpen, setIsMediaLibOpen] = useState(false);
  const [isAIPanelOpen, setIsAIPanelOpen] = useState(false);
  const [stats, setStats] = useState(null);

  const maxWords = attribute?.options?.maxLengthWords;
  const maxCharacters = attribute?.options?.maxLengthCharacters;
  const isOverLimit =
    (!!maxWords && stats?.words > maxWords) ||
    (!!maxCharacters && stats?.characters > maxCharacters);

  const resolvedLabel =
    label ??
    (typeof intlLabel === "string"
      ? intlLabel
      : intlLabel?.id != null
      ? formatMessage(intlLabel)
      : name?.match(/[^.]*$/)?.[0]);

  const handleEditorChange = (data) => onChange({ target: { name, value: data, type: "richtext" } });

  const handleEditorReady = (editor) => {
    editorRef.current = editor;

    if (editor.plugins.has("StrapiMediaLib")) {
      editor.plugins.get("StrapiMediaLib").connect(() => setIsMediaLibOpen(true));
    }

    if (editor.plugins.has("CKStudioAI")) {
      editor.plugins.get("CKStudioAI").connect(() => setIsAIPanelOpen(true));
    }
  };

  const handleSelectAssets = (html) => {
    const editor = editorRef.current;

    if (editor && html) {
      const viewFragment = editor.data.processor.toView(html);
      const modelFragment = editor.data.toModel(viewFragment);
      editor.model.insertContent(modelFragment);
    }

    setIsMediaLibOpen(false);
  };

  const renderStats = () => {
    if (!stats) return null;

    const wordsLabel = formatMessage({ id: "ckstudio.count.words", defaultMessage: "Words" });
    const charactersLabel = formatMessage({
      id: "ckstudio.count.characters",
      defaultMessage: "Characters",
    });

    return (
      <Typography variant="pi" textColor={isOverLimit ? "danger600" : "neutral500"}>
        {wordsLabel}: {stats.words}
        {maxWords ? ` / ${maxWords}` : ""} · {charactersLabel}: {stats.characters}
        {maxCharacters ? ` / ${maxCharacters}` : ""}
      </Typography>
    );
  };

  return (
    <Field.Root id={name} name={name} error={error} hint={hint} required={required}>
      <EditorGlobalStyles />
      <Field.Label action={labelAction}>{resolvedLabel}</Field.Label>
      <div className="ckstudio-editor">
        <CKEReact
          key={`${preset.name}:${presetsVersion}`}
          preset={preset}
          value={value ?? ""}
          disabled={disabled}
          onChange={handleEditorChange}
          onEditorReady={handleEditorReady}
          onWordCountUpdate={setStats}
        />
      </div>
      {renderStats()}
      <MediaLib
        isOpen={isMediaLibOpen}
        onClose={() => setIsMediaLibOpen(false)}
        onSelectAssets={handleSelectAssets}
      />
      <AIPanel
        isOpen={isAIPanelOpen}
        onClose={() => setIsAIPanelOpen(false)}
        getEditor={() => editorRef.current}
      />
      <Field.Error />
      <Field.Hint />
    </Field.Root>
  );
};

CKStudioField.propTypes = {
  name: PropTypes.string.isRequired,
  value: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  attribute: PropTypes.object,
  error: PropTypes.string,
  required: PropTypes.bool,
  disabled: PropTypes.bool,
  hint: PropTypes.node,
  labelAction: PropTypes.node,
  intlLabel: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.shape({ id: PropTypes.string, defaultMessage: PropTypes.string }),
  ]),
  label: PropTypes.node,
};

export default CKStudioField;
