import { useEffect } from "react"; import { useForm, useWatch } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material"; import { Text } from "@/components/ui/text"; import { useVendorPortal } from "@/app/v/_components/vendor-portal-context"; import { vendorPortalApi } from "@/domain/vendor-portal/api/vendor-portal-api"; import { REFUSE_REASON_MAX_LENGTH, refuseDispatchSchema, type RefuseDispatchValues, } from "@/domain/vendor-portal/schemas/refuse-dispatch-schema"; import { queryKeys } from "@/infra/query-key/query-key"; import { guardDialogClose } from "@/lib/dialog-guard"; type RefuseDispatchDialogProps = { open: boolean; dispatchId: number; onClose: () => void; onRefused: () => void; }; export function RefuseDispatchDialog({ open, dispatchId, onClose, onRefused, }: RefuseDispatchDialogProps) { const { token } = useVendorPortal(); const queryClient = useQueryClient(); const { register, handleSubmit, control, reset, formState: { errors }, } = useForm({ resolver: zodResolver(refuseDispatchSchema), mode: "onChange", defaultValues: { reason: "" }, }); const reasonValue = useWatch({ control, name: "reason" }) ?? ""; const isOverLimit = reasonValue.length > REFUSE_REASON_MAX_LENGTH; const refuseMutation = useMutation({ mutationFn: (values: RefuseDispatchValues) => { const trimmed = values.reason.trim(); return vendorPortalApi.refuse(token, dispatchId, trimmed || undefined); }, onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.vendorPortal.dispatch(token, dispatchId), }), queryClient.invalidateQueries({ queryKey: queryKeys.vendorPortal.dispatches(token), }), ]); onRefused(); onClose(); }, }); const { reset: resetMutation } = refuseMutation; useEffect(() => { if (!open) { reset({ reason: "" }); resetMutation(); } }, [open, reset, resetMutation]); const submit = handleSubmit((values) => refuseMutation.mutate(values)); const errorMessage = refuseMutation.error ? "Unable to refuse this dispatch. Please try again." : ""; return ( Refuse dispatch
void submit(event)}> Refusing ends your assignment for this dispatch. A reason is optional but helps your dispatcher reassign the work.