'use client';

import { useState, useRef, useEffect } from 'react';

interface SimpleTextEditorProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  minHeight?: string;
}

export default function SimpleTextEditor({ 
  value, 
  onChange, 
  placeholder = "Enter description...", 
  disabled = false,
  className = "",
  minHeight = "150px"
}: SimpleTextEditorProps) {
  const [isEditing, setIsEditing] = useState(false);
  const editorRef = useRef<HTMLDivElement>(null);

  const handleEdit = () => {
    if (disabled) return;
    setIsEditing(true);
  };

  const handleSave = () => {
    if (editorRef.current) {
      const newContent = editorRef.current.innerHTML;
      onChange(newContent);
    }
    setIsEditing(false);
  };

  const handleCancel = () => {
    if (editorRef.current) {
      editorRef.current.innerHTML = value;
    }
    setIsEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      handleCancel();
    }
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
      handleSave();
    }
  };

  const formatText = (command: string, value?: string) => {
    document.execCommand(command, false, value);
    if (editorRef.current) {
      editorRef.current.focus();
    }
  };

  useEffect(() => {
    if (editorRef.current && isEditing) {
      editorRef.current.focus();
    }
  }, [isEditing]);

  if (!isEditing) {
    return (
      <div className={`simple-text-display ${className}`}>
        <div 
          className="text-content"
          dangerouslySetInnerHTML={{ __html: value || placeholder }}
          onClick={handleEdit}
          style={{ 
            minHeight,
            cursor: disabled ? 'default' : 'pointer',
            opacity: !value ? 0.6 : 1
          }}
        />
        {!disabled && (
          <button 
            type="button"
            className="edit-btn"
            onClick={handleEdit}
            title="Click to edit"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="m18.5 2.5 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        )}
      </div>
    );
  }

  return (
    <div className={`simple-text-editor ${className}`}>
      <div className="toolbar">
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('bold')}
          className="toolbar-btn"
          title="Bold"
        >
          <strong>B</strong>
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('italic')}
          className="toolbar-btn"
          title="Italic"
        >
          <em>I</em>
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('underline')}
          className="toolbar-btn"
          title="Underline"
        >
          <u>U</u>
        </button>
        <div className="toolbar-divider"></div>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('insertUnorderedList')}
          className="toolbar-btn"
          title="Bullet List"
        >
          •
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('insertOrderedList')}
          className="toolbar-btn"
          title="Numbered List"
        >
          1.
        </button>
      </div>
      
      <div
        ref={editorRef}
        contentEditable
        className="editor-content"
        dangerouslySetInnerHTML={{ __html: value }}
        onKeyDown={handleKeyDown}
        style={{ minHeight }}
        data-placeholder={placeholder}
      />
      
      <div className="editor-actions">
        <button 
          type="button"
          onClick={handleSave}
          className="save-btn"
        >
          Save
        </button>
        <button 
          type="button"
          onClick={handleCancel}
          className="cancel-btn"
        >
          Cancel
        </button>
        <small className="editor-hint">
          Press Ctrl+Enter to save, Esc to cancel
        </small>
      </div>
    </div>
  );
}