"use client"; import { useEffect, useState, type FormEvent } from "react"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"; import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; export function ProfileForm({ name: initialName, email, image: initialImage }: { name: string; email: string; image: string | null; }) { const [name, setName] = useState(initialName); const [file, setFile] = useState(null); const [preview, setPreview] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]); function chooseFile(next: File | null) { setError(""); if (next && (next.size > 6 * 1024 * 1024 || !["image/png", "image/jpeg", "image/webp"].includes(next.type))) { setError("ใช้รูป PNG, JPEG หรือ WebP ขนาดไม่เกิน 6 MB"); return; } setFile(next); setPreview(next ? URL.createObjectURL(next) : null); } async function save(event: FormEvent) { event.preventDefault(); if (busy) return; setBusy(true); setError(""); try { const form = new FormData(); form.set("name", name.trim()); if (file) form.set("image", file); const response = await fetch("/api/profile", { method: "POST", body: form }); if (!response.ok) throw new Error("บันทึกโปรไฟล์ไม่สำเร็จ กรุณาลองอีกครั้ง"); window.location.reload(); } catch (cause) { setError(cause instanceof Error ? cause.message : "บันทึกโปรไฟล์ไม่สำเร็จ"); setBusy(false); } } return ข้อมูลบัญชี{email}
รูปโปรไฟล์
{(preview || initialImage) && } {name.trim().charAt(0).toUpperCase() || "?"} { const selected = event.target.files?.[0] ?? null; chooseFile(selected); if (selected && (selected.size > 6 * 1024 * 1024 || !["image/png", "image/jpeg", "image/webp"].includes(selected.type))) event.target.value = ""; }} disabled={busy} />
ชื่อที่แสดง setName(event.target.value)} minLength={2} maxLength={80} required disabled={busy} /> {error && {error}}
; }