"use client"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import * as z from "zod"; import { getUserDetail, updateUser } from "@/pages/users/lib/api"; import { useMutation, useQuery } from "@tanstack/react-query"; import formatPhone from "@/shared/lib/formatPhone"; import onlyNumber from "@/shared/lib/onlyNumber"; import { Button } from "@/shared/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/shared/ui/form"; import { Input } from "@/shared/ui/input"; import { ArrowLeft, Loader2, Mail, Phone, Save, User } from "lucide-react"; import { useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useNavigate, useParams } from "react-router-dom"; const formSchema = z .object({ first_name: z .string() .min(3, "Ism kamida 3 ta belgidan iborat bo‘lishi kerak") .nonempty("Ism majburiy"), last_name: z .string() .min(3, "Familiya kamida 3 ta belgidan iborat bo‘lishi kerak") .nonempty("Familiya majburiy"), email: z.string().email("Email formati noto‘g‘ri").or(z.literal("")), phone: z.string().min(9, "Telefon raqam to‘liq emas").or(z.literal("+998")), }) .refine((data) => data.email || data.phone, { message: "Email yoki telefon raqami kiritilishi shart", path: ["contact"], }); export default function EditUser() { const navigate = useNavigate(); const { id } = useParams(); const { t } = useTranslation(); const { data } = useQuery({ queryKey: ["user_detail", id], queryFn: () => getUserDetail({ id: Number(id) }), }); const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { first_name: "", last_name: "", email: "", phone: "+998", }, }); useEffect(() => { if (data) { const u = data.data.data; form.reset({ first_name: u.first_name, last_name: u.last_name, email: u.email || "", phone: formatPhone(u.phone), }); } }, [data, form]); const { mutate, isPending } = useMutation({ mutationFn: ({ body, id, }: { body: { first_name: string; last_name: string; email: string | null; phone: string | null; }; id: number; }) => updateUser({ body, id }), onSuccess: () => navigate("/user"), }); const onSubmit = (values: z.infer) => { if (data) { mutate({ body: { first_name: values.first_name, last_name: values.last_name, email: values.email.length === 0 ? null : values.email, phone: values.phone.length === 0 ? null : onlyNumber(values.phone), }, id: data.data.data.id, }); } }; return (
{/* Header */}

{t("Tahrirlash")}

{t("Ma'lumotlarni yangilang")}

{/* Form */}
{/* First Name */} ( {t("Ismi")}
)} /> {/* Last Name */} ( {t("Familiyasi")}
)} /> {/* Email */} ( {t("Email")}
)} /> {/* Phone */} ( {t("Telefon raqami")}
field.onChange(e.target.value)} placeholder="+998 90 123 45 67" className="pl-10 h-11 bg-slate-800/50 text-slate-200 border-slate-700/50 focus:border-emerald-500" />
)} /> {/* Submit buttons */}
); }