import { useEffect, useRef, useState } from "react";
const initialState = {
  question: "",
  answer: ""
};
export function EntryForm({ onSubmit, onCancel, initialValue, saving }) {
  const [form, setForm] = useState(initialState);
  const formRef = useRef(null);
  useEffect(() => {
    setForm(initialValue || initialState);
    if (formRef.current) {
      formRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
      formRef.current.querySelector("input")?.focus();
    }
  }, [initialValue]);
  return (
    <form
      className="editor-panel"
      ref={formRef}
      onSubmit={(event) => {
        event.preventDefault();
        onSubmit(form);
      }}
      style={{ display: "flex", flexDirection: "column", gap: "32px" }}
    >
      <div className="field-group">
        <label className="field-label" htmlFor="question" style={{ display: "block", marginBottom: "12px", fontSize: "11px", textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-muted)" }}>
          Question
        </label>
        <textarea
          id="question"
          rows="2"
          style={{ minHeight: "80px", width: "100%", padding: "16px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-subtle)", background: "var(--bg-input)", color: "var(--text-primary)", fontSize: "16px" }}
          value={form.question}
          onChange={(event) => setForm((current) => ({ ...current, question: event.target.value }))}
          placeholder="What do you want to remember?"
        />
      </div>

      <div className="field-group">
        <label className="field-label" htmlFor="answer" style={{ display: "block", marginBottom: "12px", fontSize: "11px", textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-muted)" }}>
          Answer (Markdown)
        </label>
        <textarea
          id="answer"
          rows="12"
          style={{ minHeight: "300px", width: "100%", padding: "16px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-subtle)", background: "var(--bg-input)", color: "var(--text-primary)", fontSize: "16px", fontFamily: "inherit" }}
          value={form.answer}
          onChange={(event) => setForm((current) => ({ ...current, answer: event.target.value }))}
          placeholder="Markdown renders as formatted answer output."
        />
      </div>

      <div className="form-actions" style={{ display: "flex", gap: "12px", paddingTop: "16px" }}>
        <button className="button-primary" disabled={saving} style={{ flex: 1, padding: "16px" }} type="submit">
          {saving ? "Saving..." : "Save to Library"}
        </button>
        <button className="button-ghost" onClick={onCancel} style={{ padding: "16px 24px" }} type="button">
          Cancel
        </button>
      </div>
    </form>
  );
}
