"use client"; import Link from "next/link"; import { useState, type FormEvent } from "react"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { authClient } from "@/lib/auth/client"; type Mode = "forgot" | "reset"; export function EmailActionForm({ mode, token = "", invalidToken = false, nextPath = "/" }: { mode: Mode; token?: string; invalidToken?: boolean; nextPath?: string; }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [sent, setSent] = useState(false); async function submit(event: FormEvent) { event.preventDefault(); if (busy) return; const form = new FormData(event.currentTarget); const address = String(form.get("email") ?? "").trim(); setBusy(true); setError(""); try { if (mode === "forgot") { const returnQuery = nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`; const result = await authClient.requestPasswordReset({ email: address, redirectTo: `/auth/password-reset${returnQuery}` }); if (result.error) throw new Error("ส่งลิงก์รีเซ็ตไม่สำเร็จ กรุณาลองอีกครั้ง"); } else { const password = String(form.get("password") ?? ""); if (password !== String(form.get("confirmPassword") ?? "")) { setError("รหัสผ่านใหม่ไม่ตรงกัน"); return; } const result = await authClient.resetPassword({ newPassword: password, token }); if (result.error) throw new Error("รีเซ็ตรหัสผ่านไม่สำเร็จ ลิงก์อาจหมดอายุแล้ว"); } setSent(true); } catch (cause) { setError(cause instanceof Error ? cause.message : "ลองอีกครั้ง"); } finally { setBusy(false); } } const title = mode === "forgot" ? "ลืมรหัสผ่าน" : "ตั้งรหัสผ่านใหม่"; const loginHref = `/auth/login${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`; const canReset = Boolean(token) && !invalidToken; return {title} {sent && {mode === "reset" ? "ตั้งรหัสผ่านใหม่แล้ว กรุณาเข้าสู่ระบบ" : "หากอีเมลนี้มีบัญชีอยู่ โปรดตรวจสอบกล่องจดหมายและโฟลเดอร์สแปม"}} {invalidToken && ลิงก์รีเซ็ตไม่ถูกต้องหรือหมดอายุ กรุณาขอลิงก์ใหม่ } {error && {error}} {(mode !== "reset" || (!sent && canReset)) &&
{mode !== "reset" ? อีเมล : <> รหัสผ่านใหม่ ยืนยันรหัสผ่านใหม่ }
} {mode === "reset" && !canReset && !sent && }
; }