import React, { useEffect, useState } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

export default function HelpEditor() {
  const [helpItems, setHelpItems] = useState({});
  const [selectedKey, setSelectedKey] = useState('');
  const [newKey, setNewKey] = useState('');
  const [title, setTitle] = useState('');
  const [text, setText] = useState('');

  useEffect(() => {
    fetch('http://localhost:8080/api/help?lang=en')
      .then(res => res.json())
      .then(setHelpItems);
  }, []);

  const saveItem = () => {
    const key = newKey || selectedKey;
    if (!key.trim()) {
      alert('Keyword is required');
      return;
    }

    const updated = { ...helpItems, [key]: { title, text } };
    fetch('http://localhost:8080/api/help', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updated),
    }).then(() => {
      setHelpItems(updated);
      if (newKey) {
        setSelectedKey(newKey);
        setNewKey('');
      }
      alert('Saved!');
    });
  };

  const loadItem = (key) => {
    setSelectedKey(key);
    setNewKey('');
    setTitle(helpItems[key].title);
    setText(helpItems[key].text);
  };

  return (
    <div style={{ padding: '20px', maxWidth: '700px', margin: '0 auto' }}>
      <h2>Edit or Add Help Content</h2>

      <div style={{ marginBottom: '1rem' }}>
        <label>
          Existing Keywords:&nbsp;
          <select value={selectedKey} onChange={e => loadItem(e.target.value)}>
            <option value="">-- Select --</option>
            {Object.keys(helpItems).map(key => (
              <option key={key} value={key}>{key}</option>
            ))}
          </select>
        </label>
      </div>

      <div style={{ marginBottom: '1rem' }}>
        <label>
          Or enter a new keyword:&nbsp;
          <input
            type="text"
            placeholder="e.g., repayment_terms"
            value={newKey}
            onChange={e => {
              setNewKey(e.target.value);
              setSelectedKey('');
              setTitle('');
              setText('');
            }}
          />
        </label>
      </div>

      <input
        type="text"
        placeholder="Title"
        value={title}
        onChange={e => setTitle(e.target.value)}
        style={{ width: '100%', marginBottom: '1rem', padding: '8px' }}
      />

      <ReactQuill theme="snow" value={text} onChange={setText} style={{ marginBottom: '1rem' }} />

      <button onClick={saveItem} style={{ padding: '10px 20px' }}>
        Save
      </button>
    </div>
  );
}

