"use client";
import { useRef, useState, type FormEvent } from "react";
import styles from "./ContentStudy.module.css";

export function ValidationExample() {
  const [email, setEmail] = useState("");
  const [goal, setGoal] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [complete, setComplete] = useState(false);
  const summary = useRef<HTMLDivElement>(null);
  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const next: Record<string, string> = {};
    const emailInput = event.currentTarget.elements.namedItem("demo-email") as HTMLInputElement;
    if (!email.trim()) next["demo-email"] = "Enter an email address so we can reply.";
    else if (emailInput.validity.typeMismatch) next["demo-email"] = "Enter an email address in the format name@example.com.";
    if (!goal.trim()) next["demo-goal"] = "Describe the main result you want from this project.";
    setErrors(next);
    setComplete(Object.keys(next).length === 0);
    if (Object.keys(next).length) requestAnimationFrame(() => summary.current?.focus());
  }
  return <section className={styles.study} aria-labelledby="validation-demo-title">
    <h2 id="validation-demo-title">Try the validation example</h2>
    <p>Use fictional details. This demonstration sends and saves nothing.</p>
    <form noValidate onSubmit={submit} className="space-y-5">
      {!!Object.keys(errors).length && <div ref={summary} tabIndex={-1} role="alert" className="rounded border-2 border-red-700 p-4">
        <h3>Please correct the fields below</h3>
        <ul>{Object.entries(errors).map(([id, message]) => <li key={id}><a href={"#" + id} onClick={event => { event.preventDefault(); document.getElementById(id)?.focus(); }}>{message}</a></li>)}</ul>
      </div>}
      <div><label htmlFor="demo-email" className="block font-semibold">Reply email (required)</label>
        <p id="demo-email-hint">Example: alex@example.com</p>
        <input id="demo-email" name="demo-email" type="email" required autoComplete="off" value={email} onChange={e => {setEmail(e.target.value); setComplete(false);}} aria-invalid={!!errors["demo-email"]} aria-describedby={"demo-email-hint" + (errors["demo-email"] ? " demo-email-error" : "")} className="w-full rounded border border-current bg-background p-3" />
        {errors["demo-email"] && <p id="demo-email-error">Error: {errors["demo-email"]}</p>}
      </div>
      <div><label htmlFor="demo-goal" className="block font-semibold">Main project goal (required)</label>
        <textarea id="demo-goal" name="demo-goal" required rows={3} value={goal} onChange={e => {setGoal(e.target.value); setComplete(false);}} aria-invalid={!!errors["demo-goal"]} aria-describedby={errors["demo-goal"] ? "demo-goal-error" : undefined} className="w-full rounded border border-current bg-background p-3" />
        {errors["demo-goal"] && <p id="demo-goal-error">Error: {errors["demo-goal"]}</p>}
      </div>
      <button type="submit" className="rounded bg-primary px-5 py-3 font-semibold text-primary-foreground">Check example</button>
      <p role="status" aria-live="polite">{complete ? "Example complete. Nothing was sent or saved." : ""}</p>
    </form>
  </section>;
}
