← back to Homesonspec

apps/web/src/app/homes/[id]/CorrectionForm.tsx

76 lines

"use client";

import { useState } from "react";

/** "Report a problem" — the consumer-facing correction control. */
export default function CorrectionForm({ entityId }: { entityId: string }) {
  const [open, setOpen] = useState(false);
  const [message, setMessage] = useState("");
  const [email, setEmail] = useState("");
  const [state, setState] = useState<"idle" | "sending" | "done" | "error">("idle");

  if (state === "done") {
    return <p className="text-sm text-emerald-700" data-testid="correction-done">Thanks — your report is in our review queue.</p>;
  }

  return (
    <div>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="text-sm text-neutral-500 underline hover:text-teal-700"
        data-testid="correction-toggle"
      >
        Report a problem with this listing
      </button>
      {open && (
        <form
          className="mt-3 max-w-md space-y-2 rounded-lg border border-neutral-200 p-3 text-sm"
          onSubmit={async (e) => {
            e.preventDefault();
            setState("sending");
            const res = await fetch("/api/corrections", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                entityType: "INVENTORY_HOME",
                entityId,
                message,
                reporterEmail: email || undefined,
              }),
            });
            setState(res.ok ? "done" : "error");
          }}
        >
          <textarea
            required
            minLength={3}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder="What looks wrong? (price, availability, address…)"
            className="w-full rounded border border-neutral-300 px-2 py-1"
            rows={3}
            data-testid="correction-message"
          />
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Your email (optional)"
            className="w-full rounded border border-neutral-300 px-2 py-1"
          />
          <button
            type="submit"
            disabled={state === "sending"}
            className="rounded bg-neutral-800 px-4 py-1.5 text-white disabled:opacity-50"
            data-testid="correction-submit"
          >
            {state === "sending" ? "Sending…" : "Send report"}
          </button>
          {state === "error" && <p className="text-red-600">Could not send — try again.</p>}
        </form>
      )}
    </div>
  );
}