"use client";

import { FormEvent, useState } from "react";

export default function PasswordSetup({ email, isReset }: { email: string; isReset: boolean }) {
  const [password, setPassword] = useState("");
  const [confirmation, setConfirmation] = useState("");
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  async function submit(event: FormEvent) {
    event.preventDefault(); setBusy(true); setMessage("");
    const response = await fetch("/api/dealer/auth/set-password", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password, confirmation }) });
    const data = await response.json(); setBusy(false);
    if (response.ok) window.location.href = data.redirect || "/dealer/dashboard";
    else setMessage(data.error || "Password could not be saved.");
  }
  return <main className="dealer-auth-page"><section className="dealer-auth-brand"><img src="/logo-reversed.svg" alt="Beat My Car Quote" /><p className="eyebrow-text">Email verified</p><h1>{isReset ? "Reset your secure portal password." : "Finish setting up your dealer account."}</h1><p>After this step, sign in with your business email and password whenever you need to review opportunities or submit pricing.</p></section><section className="dealer-auth-card"><p className="eyebrow-text">Account security</p><h2>{isReset ? "Create a new password" : "Create your password"}</h2><p>Your account name is <strong>{email}</strong>. Use at least 12 characters, including a letter and a number.</p><form onSubmit={submit}><label><span>Account email</span><input value={email} readOnly autoComplete="username" /></label><label><span>New password</span><input type="password" required minLength={12} maxLength={128} autoComplete="new-password" value={password} onChange={(event) => setPassword(event.target.value)} /></label><label><span>Confirm password</span><input type="password" required minLength={12} maxLength={128} autoComplete="new-password" value={confirmation} onChange={(event) => setConfirmation(event.target.value)} /></label><button className="button" disabled={busy}>{busy ? "Saving…" : "Save password and continue"}</button></form>{message && <p className="portal-message" role="alert">{message}</p>}</section></main>;
}
