import { useEffect, useState } from "react";

const initialState = {
  question: "",
  answer: ""
};

export function EntryForm({ onSubmit, onCancel, initialValue, saving }) {
  const [form, setForm] = useState(initialState);

  useEffect(() => {
    setForm(initialValue || initialState);
  }, [initialValue]);

  return (
    <form
      className="editor-panel"
      onSubmit={(event) => {
        event.preventDefault();
        onSubmit(form);
      }}
    >
      <label className="field-label" htmlFor="question">
        Question
      </label>
      <input
        id="question"
        value={form.question}
        onChange={(event) => setForm((current) => ({ ...current, question: event.target.value }))}
        placeholder="What do you want to remember?"
      />
      <label className="field-label" htmlFor="answer">
        Answer (Markdown supported)
      </label>
      <textarea
        id="answer"
        rows="10"
        value={form.answer}
        onChange={(event) => setForm((current) => ({ ...current, answer: event.target.value }))}
        placeholder="Markdown renders as formatted answer output."
      />
      <div className="form-actions">
        <button className="button-primary" disabled={saving} type="submit">
          {saving ? "Saving..." : "Save Entry"}
        </button>
        <button className="button-ghost" onClick={onCancel} type="button">
          Cancel
        </button>
      </div>
    </form>
  );
}
