import React, { useState } from 'react';
import { Button } from '@mantine/core';
import { useEditor } from '@tiptap/react';
import { Link, RichTextEditor } from '@mantine/tiptap';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import CommentAttachmentInput, { CommentAttachmentChips } from './CommentAttachmentInput';
import { __ } from '@wordpress/i18n';

// Inline editor for an existing comment's text, plus new files to attach on
// save. Mounted only for the one comment being edited, so it's the only place a
// second Tiptap instance ever exists alongside the composer's. Saved files are
// removed through their own pills (CommentAttachments), not here.
//
// hasAttachments: the comment already carries files, so clearing the text is
// allowed — same rule as posting: text, files, or both.
const CommentEditForm = ({ initialContent, onSave, onCancel, saving, hasAttachments = false, className = '' }) => {
  const [content, setContent] = useState(initialContent || '');
  const [files, setFiles] = useState([]);
  const editEditor = useEditor({
    extensions: [
      StarterKit,
      Link.configure({
        autolink: true,
        linkOnPaste: true,
        openOnClick: true,
        HTMLAttributes: { target: '_blank', rel: 'noopener noreferrer' }
      }),
      Underline,
    ],
    content: initialContent || '',
    onUpdate: ({ editor }) => setContent(editor.getHTML()),
  });
  const isTextEmpty = !content || content.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, '').trim() === '';
  const isEmpty = isTextEmpty && files.length === 0 && !hasAttachments;

  // Same card as the add-comment composer: borderless editor, then a divider
  // row with formatting on the left and attach + actions on the right.
  return (
    <div className={`w-full ${className}`}>
      <div className="bg-white border border-[#E2E8F0] shadow-sm rounded-xl p-4">
        <RichTextEditor editor={editEditor} className="border-0 !p-0">
          <RichTextEditor.Content
            className="prose prose-sm min-h-[60px]"
            spellCheck={false}
            style={{ maxHeight: '210px', overflowY: 'auto' }}
          />

          <div className="flex justify-between items-center mt-3 pt-3 border-t border-[#F1F5F9]">
            <RichTextEditor.Toolbar className="border-0 p-0 bg-transparent">
              <RichTextEditor.ControlsGroup>
                <RichTextEditor.Bold />
                <RichTextEditor.Italic />
                <RichTextEditor.Underline />
                <RichTextEditor.Strikethrough />
                <RichTextEditor.Link />
              </RichTextEditor.ControlsGroup>
            </RichTextEditor.Toolbar>
            <div className="flex items-center gap-2">
              <CommentAttachmentInput files={files} onChange={setFiles} disabled={saving} />
              <Button radius="md" variant="default" size="sm" onClick={onCancel} disabled={saving}>{__('Cancel', 'lazytasks-project-task-management')}</Button>
              <Button radius="md" color="#2563EB" size="sm" onClick={() => onSave(isTextEmpty ? '' : content, files)} disabled={saving || isEmpty}>{__('Save', 'lazytasks-project-task-management')} ➔</Button>
            </div>
          </div>
          <CommentAttachmentChips files={files} onChange={setFiles} />
        </RichTextEditor>
      </div>
    </div>
  );
};

export default CommentEditForm;
