'use client';

import { useEffect, useRef, useState } from 'react';

const CKEDITOR_SCRIPT_ID = 'ckeditor5-classic-cdn';
const CKEDITOR_SRC =
  'https://cdn.jsdelivr.net/npm/@ckeditor/ckeditor5-build-classic@41.4.2/build/ckeditor.js';

type ClassicEditorInstance = {
  getData: () => string;
  setData: (data: string) => void;
  destroy: () => Promise<void>;
  model: {
    document: {
      on: (event: string, callback: () => void) => void;
    };
  };
};

type ClassicEditorStatic = {
  create: (
    element: HTMLElement,
    config?: Record<string, unknown>
  ) => Promise<ClassicEditorInstance>;
};

declare global {
  interface Window {
    ClassicEditor?: ClassicEditorStatic;
  }
}

type RichTextEditorProps = {
  data: string;
  onChange: (data: string) => void;
  placeholder?: string;
  config?: Record<string, unknown>;
};

function loadClassicEditor(): Promise<ClassicEditorStatic> {
  if (typeof window !== 'undefined' && window.ClassicEditor) {
    return Promise.resolve(window.ClassicEditor);
  }

  return new Promise((resolve, reject) => {
    const existing = document.getElementById(CKEDITOR_SCRIPT_ID) as HTMLScriptElement | null;
    if (existing) {
      existing.addEventListener('load', () => {
        if (window.ClassicEditor) resolve(window.ClassicEditor);
        else reject(new Error('CKEditor failed to load'));
      });
      existing.addEventListener('error', () => reject(new Error('CKEditor failed to load')));
      return;
    }

    const script = document.createElement('script');
    script.id = CKEDITOR_SCRIPT_ID;
    script.src = CKEDITOR_SRC;
    script.async = true;
    script.onload = () => {
      if (window.ClassicEditor) resolve(window.ClassicEditor);
      else reject(new Error('CKEditor failed to load'));
    };
    script.onerror = () => reject(new Error('CKEditor failed to load'));
    document.body.appendChild(script);
  });
}

export default function RichTextEditor({
  data,
  onChange,
  placeholder = 'Start typing here...',
  config,
}: RichTextEditorProps) {
  const hostRef = useRef<HTMLDivElement | null>(null);
  const editorRef = useRef<ClassicEditorInstance | null>(null);
  const onChangeRef = useRef(onChange);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);

  useEffect(() => {
    let cancelled = false;

    async function init() {
      if (!hostRef.current) return;

      try {
        setIsLoading(true);
        setError(null);
        const ClassicEditor = await loadClassicEditor();
        if (cancelled || !hostRef.current) return;

        const editor = await ClassicEditor.create(hostRef.current, {
          placeholder,
          ...config,
        });

        if (cancelled) {
          await editor.destroy();
          return;
        }

        editor.setData(data || '');
        editor.model.document.on('change:data', () => {
          onChangeRef.current(editor.getData());
        });
        editorRef.current = editor;
        setIsLoading(false);
      } catch (err) {
        console.error(err);
        if (!cancelled) {
          setError('Unable to load editor');
          setIsLoading(false);
        }
      }
    }

    void init();

    return () => {
      cancelled = true;
      const editor = editorRef.current;
      editorRef.current = null;
      if (editor) {
        void editor.destroy();
      }
    };
    // Intentionally mount-once; parent form owns content via onChange
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    const editor = editorRef.current;
    if (!editor) return;
    if (editor.getData() !== data) {
      editor.setData(data || '');
    }
  }, [data]);

  return (
    <div className="relative">
      {isLoading && (
        <div className="absolute inset-0 z-10 flex items-center justify-center bg-white/80 text-sm text-gray-500">
          Loading editor…
        </div>
      )}
      {error && (
        <div className="mb-2 rounded border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          {error}
        </div>
      )}
      <div ref={hostRef} className="min-h-[450px]" />
    </div>
  );
}
