"use client"; import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; import { Alert, Button, Input, Modal } from "../UI"; import { createBranchSchema, updateBranchSchema } from "@/src/validations/branch.validator"; import type { Branch, BranchFormData } from "@/src/types/branch"; const FORM_ID = "branch-form"; // ── Props ───────────────────────────────────────────────────────────────────── interface BranchFormModalProps { editBranch: Branch | null; onClose: () => void; onSubmit: (data: BranchFormData, isNew: boolean) => Promise; } // ── main component ──────────────────────────────────────────────────────────── export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormModalProps) { const isNew = editBranch === null; const { register, handleSubmit, setError, formState: { errors, isSubmitting }, } = useForm({ // Cast the schema itself and pin the generic explicitly on yupResolver — // create/update schemas differ structurally in which fields are required // (e.g. city/street are optional on update), so yup can't unify them // into the single flat BranchFormData shape on its own. resolver: yupResolver((isNew ? createBranchSchema : updateBranchSchema) as any), defaultValues: { name: editBranch?.name ?? "", email: editBranch?.email ?? "", phone: editBranch?.phone ?? "", country: editBranch?.country ?? "SA", city: editBranch?.city ?? "", state: editBranch?.state ?? "", district: editBranch?.district ?? "", street: editBranch?.street ?? "", buildingNo: editBranch?.buildingNo ?? "", unitNo: editBranch?.unitNo ?? "", zipCode: editBranch?.zipCode ?? "", latitude: editBranch?.latitude != null ? String(editBranch.latitude) : "", longitude: editBranch?.longitude != null ? String(editBranch.longitude) : "", }, }); const submitHandler = async (data: BranchFormData) => { const ok = await onSubmit(data, isNew); if (ok) { onClose(); } else { setError("name", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." }); } }; return ( } >
{errors.name?.type === "manual" && ( {}} /> )} {/* name */} {/* email + phone */}
{/* city + street */}
{/* state + district */}
{/* buildingNo + unitNo + zipCode */}
{/* country */} {/* latitude + longitude */}
); }