'use client';

import { EditorContent, useEditor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import { useEffect } from 'react';

export type EditorJson = Record<string, any>;

type Props = {
  label: string;
  value: EditorJson | null;
  onChange: (value: EditorJson) => void;
  placeholder?: string;
};

export default function RichTextEditor({
  label,
  value,
  onChange,
  placeholder,
}: Props) {
  const editor = useEditor({
    immediatelyRender: false,
    extensions: [
      StarterKit.configure({
        heading: false,
        orderedList: false,
      }),
    ],
    content: value ?? {
      type: 'doc',
      content: [{ type: 'paragraph' }],
    },
    editorProps: {
      attributes: {
        class:
          'focus:outline-none min-h-[120px] text-sm leading-6 ' +
          '[&_p]:my-2 ' +
          '[&_ul]:list-disc [&_ul]:pl-6 [&_ul]:my-2 ' +
          '[&_li]:my-1 ' +
          '[&_strong]:font-semibold ' +
          '[&_em]:italic',
      },
    },
    onUpdate({ editor }) {
      onChange(editor.getJSON());
    },
  });

  // Sync externe → éditeur (si nécessaire)
  useEffect(() => {
    if (editor && value && JSON.stringify(editor.getJSON()) !== JSON.stringify(value)) {
      editor.commands.setContent(value);
    }
  }, [value, editor]);

  if (!editor) {
    return (
      <div className="rounded-md border bg-gray-50 px-3 py-2 text-sm text-gray-400">
        Chargement de l'éditeur…
      </div>
    );
  }

  const hasText = editor.getText().trim().length > 0;

  return (
    <div className="space-y-2">
      <label className="block text-sm font-medium text-gray-900">{label}</label>

      {/* Toolbar */}
      <div className="flex flex-wrap gap-1 rounded-md border bg-gray-50 p-2">
        <button
          type="button"
          onClick={() => editor.chain().focus().toggleBold().run()}
          className={`px-3 py-1.5 text-sm rounded font-semibold transition-colors ${
            editor.isActive('bold')
              ? 'bg-blue-600 text-white'
              : 'bg-white border hover:bg-gray-50'
          }`}
          aria-label="Gras"
        >
          B
        </button>

        <button
          type="button"
          onClick={() => editor.chain().focus().toggleItalic().run()}
          className={`px-3 py-1.5 text-sm rounded italic transition-colors ${
            editor.isActive('italic')
              ? 'bg-blue-600 text-white'
              : 'bg-white border hover:bg-gray-50'
          }`}
          aria-label="Italique"
        >
          I
        </button>

        <button
          type="button"//import Hero from '@/components/recruiter/hero';
          onClick={() => editor.chain().focus().toggleBulletList().run()}
          className={`px-3 py-1.5 text-sm rounded transition-colors ${
            editor.isActive('bulletList')
              ? 'bg-blue-600 text-white'
              : 'bg-white border hover:bg-gray-50'
          }`}
          aria-label="Liste à puces"
        >
          • Liste
        </button>

        <button
          type="button"
          onClick={() =>
            editor.chain().focus().clearNodes().unsetAllMarks().run()
          }
          className="px-3 py-1.5 text-sm rounded bg-white border hover:bg-gray-50 transition-colors"
          aria-label="Effacer le format"
        >
          Effacer
        </button>
      </div>

      {/* Editor */}
      <div className="rounded-md border bg-white px-3 py-2 min-h-[140px] relative">
        {placeholder && !hasText && (
          <div className="absolute top-2 left-3 pointer-events-none text-sm text-gray-400">
            {placeholder}
          </div>
        )}
        <EditorContent editor={editor} />
      </div>
    </div>
  );
}
