import {
  ClassicEditor,
  Essentials,
  Bold,
  Strikethrough,
  FontColor,
  Link,
  Alignment,
  Paragraph,
  SourceEditing,
  Image,
  ImageToolbar,
  ImageCaption,
  ImageUpload,
  LinkImage,
  SimpleUploadAdapter,
} from "ckeditor5";
import coreTranslations from "ckeditor5/translations/ja.js";

export interface CKEditorConfig {
  container: string | HTMLElement;
  placeholder?: string;
  toolbar?: string[];
  initialData?: string;
  uploadUrl?: string;
  readOnly?: boolean;
  height?: string;
  language?: string;
  translations?: object;
}

export class CKEditorWrapper {
  private editor: any = null;
  private config: CKEditorConfig;
  private defaultToolbar = [
    "bold",
    "strikethrough",
    "fontColor",
    "|",
    "link",
    "uploadImage",
    "alignment",
    "|",
    "sourceEditing",
    "|",
    "undo",
    "redo",
  ];

  constructor(config: CKEditorConfig) {
    this.config = {
      ...config,
      toolbar: config.toolbar || this.defaultToolbar,
      language: config.language || "ja", // デフォルトで日本語を設定
    };
  }

  public async init(): Promise<any> {
    try {
      const container =
        typeof this.config.container === "string"
          ? document.querySelector(this.config.container)
          : this.config.container;

      if (!container) {
        throw new Error(`Container not found: ${this.config.container}`);
      }

      // 画像アップロード先（未指定時は管理画面レイアウトの meta から取得）
      const uploadUrl =
        this.config.uploadUrl ??
        document.querySelector<HTMLMetaElement>(
          'meta[name="content-image-upload-url"]'
        )?.content;
      const csrfToken =
        document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')
          ?.content ?? "";

      this.editor = await ClassicEditor.create(container as HTMLElement, {
        licenseKey:
          "eyJhbGciOiJFUzI1NiJ9.eyJleHAiOjE3NzAyNDk1OTksImp0aSI6IjBmZjE4MDc0LTYzZDgtNDkzOC04YzkwLTkxODY2MzAyZDNmMiIsImRpc3RyaWJ1dGlvbkNoYW5uZWwiOlsic2giLCJkcnVwYWwiXSwid2hpdGVMYWJlbCI6dHJ1ZSwiZmVhdHVyZXMiOlsiRFJVUCJdLCJ2YyI6IjdmZjZmOWY5In0.3iWogZqMXsVy7bpOTOtTuOEVDO6Zuag96DM0WfdpvP0sjaLHZ_MuHgB_XjthuCvt1RYqSup1GQFRA82Fe_t2tg", // TODO : ライセンスキーを指定
        plugins: [
          Essentials,
          Paragraph,
          Bold,
          Strikethrough,
          FontColor,
          Link,
          Alignment,
          SourceEditing,
          Image,
          ImageToolbar,
          ImageCaption,
          ImageUpload,
          LinkImage,
          SimpleUploadAdapter,
        ],
        translations: [coreTranslations],
        toolbar: {
          items: this.config.toolbar,
          shouldNotGroupWhenFull: true,
        },
        placeholder: this.config.placeholder,
        language: this.config.language,
        alignment: {
          options: [
            { name: "left", className: "text-left" },
            { name: "center", className: "text-center" },
            { name: "right", className: "text-right" },
            { name: "justify", className: "text-justify" },
          ],
        },
        image: {
          toolbar: [
            "imageTextAlternative",
            "toggleImageCaption",
            "|",
            "linkImage",
          ],
        },
        simpleUpload: uploadUrl
          ? {
              uploadUrl,
              headers: {
                "X-CSRF-TOKEN": csrfToken,
                "X-Requested-With": "XMLHttpRequest",
              },
            }
          : undefined,
        ui: {
          viewportOffset: {
            top: 64,
          },
        },
      });

      if (this.config.initialData) {
        this.editor.setData(this.config.initialData);
      }

      if (this.config.readOnly) {
        this.editor.isReadOnly = true;
      }

      if (this.config.height) {
        const editorElement = container.nextElementSibling as HTMLElement;
        if (
          editorElement &&
          editorElement.classList.contains("ck-editor__editable")
        ) {
          editorElement.style.height = this.config.height;
        }
      }

      return this.editor;
    } catch (error) {
      console.error("CKEditor initialization failed:", error);
      throw error;
    }
  }

  public getEditor(): any {
    return this.editor;
  }

  public getData(): string {
    return this.editor ? this.editor.getData() : "";
  }

  public setData(data: string): void {
    if (this.editor) {
      this.editor.setData(data);
    }
  }

  public destroy(): Promise<void> {
    return this.editor ? this.editor.destroy() : Promise.resolve();
  }
}
