quick-consultation-index.tsx

 import { background, flex } from "@ebh/capsule/theme";

import { padding, gap, border, margin, screen } from "@ebh/capsule/theme";
import { useToast } from "@ebh/capsule";
import { useNavigate } from "react-router-dom";
import { useScreen } from "@ebh/capsule/hooks";
import { FormProvider } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import { Button } from "@ebh/capsule";
import { css } from "@emotion/react";
import { useEffect, useRef } from "react";
import {
defaultQuickConsultationValues,
QuickConsultationFormData,
QuickConsultationSchema,
} from "./schema.ts";
import LoadingScreen from "../loading-screen.tsx";
import QuickConsultationForm from "./quick-consultation-form/index.tsx";
import { useState } from "react";


import { usePatientMembers } from "../../api/hooks/corporate-benfits/quick-consultation/fetch-patient-details.ts";
import { useSubmitQuickConsultation } from "../../api/hooks/corporate-benfits/quick-consultation/submit-patient-details.ts";
import { useUpdateQuickConsultation } from "../../api/hooks/corporate-benfits/quick-consultation/update-patient-details.ts";
import { AxiosError } from "axios";
import { QUICK_CONSULTATION_DETAILS } from "../../constants.ts";
import { useQuickConsultationContext } from "../../context/quick-consultation-context.tsx";
import HeaderBack from "../../components/header-back/index.tsx";
import cookiesManager from "../../utils/cookies-manager.ts";
import { calculateAge } from "../../utils/calculate-age.ts";
export default function quickConsultation() {
const navigate = useNavigate();
const isPhone = !useScreen("md");

const [selectedPatient, setSelectedPatient] = useState(false);
const [dependentSlug, setDependentSlug] = useState("");
const Toast = useToast();
const {
setConsultationDetails,
setFormData,
formData,
clearConsultationDetails,
} = useQuickConsultationContext();
const {
data: patientProfileList,
isFetching: isPatientFetching,
isLoading: isPatientLoading,
} = usePatientMembers();

const { submitConsultation, isSubmitting } = useSubmitQuickConsultation();
const { updateConsultation, isUpdating } = useUpdateQuickConsultation();

const methods = useForm<QuickConsultationFormData>({
defaultValues: defaultQuickConsultationValues,
resolver: yupResolver(QuickConsultationSchema()),
mode: "onChange",
});

const {
control,
handleSubmit,
reset,
formState: { errors },
} = methods;

const hasClearedRef = useRef(false);
useEffect(() => {
const navigationEntries = performance.getEntriesByType("navigation") as PerformanceNavigationTiming[];
const isReload = navigationEntries?.[0]?.type === "reload";
if (!hasClearedRef.current && isReload) {
clearConsultationDetails();
hasClearedRef.current = true;
}
}, []);

useEffect(() => {
if (formData) {
reset(formData);
}
}, [formData, reset]);

const isFormDisabled = !selectedPatient;
const handleReset = () => {
reset(defaultQuickConsultationValues);
};

const isLoading =
isPatientLoading || isPatientFetching || isSubmitting || isUpdating;

const submitQuickConsultation = (data: QuickConsultationFormData) => {
const isOtherPatient =
data?.quickconsultationDetails?.patientname?.toLowerCase() === "others";
const quickConsultationData = {
full_name: data?.quickconsultationDetails?.name ?? "",
gender: data?.quickconsultationDetails?.gender ?? "",
height:
Number(data?.quickconsultationDetails?.heightFt) * 12 +
Number(data?.quickconsultationDetails?.heightIn),
weight: data?.quickconsultationDetails?.weight ?? "",
dob: data?.quickconsultationDetails?.dateOfBirth ?? "",
...(isOtherPatient
? {}
: {
patient_slug_id:
dependentSlug || cookiesManager.get(QUICK_CONSULTATION_DETAILS.PATIENT_SLUG),
})
,
email: data?.quickconsultationDetails?.emailId ?? "",
phone: data?.quickconsultationDetails?.mobileNumber ?? "",
...(isOtherPatient ? { terms_and_condition: true } : {}),
};

setConsultationDetails({
patientname: data?.quickconsultationDetails?.patientname ?? "",
gender: data?.quickconsultationDetails?.gender ?? "",
relation: data?.quickconsultationDetails?.relation ?? "",
age: String(calculateAge(data?.quickconsultationDetails?.dateOfBirth)),
});
setFormData(data);
if (!selectedPatient && (dependentSlug||cookiesManager.get(QUICK_CONSULTATION_DETAILS.PATIENT_SLUG)))
{
handleUpdateConsultationAPI(quickConsultationData);
} else if (selectedPatient && !dependentSlug) {
handleSubmitConsultationAPI(quickConsultationData);
} else {
Toast("Patient selection is invalid. Please try again.", "error");
}
};

const handleSubmitConsultationAPI = (payload: any) => {
submitConsultation(payload, {
onSuccess: (data) => {
reset(defaultQuickConsultationValues);
const patientSlug = data?.patient_slug_id;
if (patientSlug) {
cookiesManager.set(
QUICK_CONSULTATION_DETAILS.PATIENT_SLUG,
patientSlug,
{
path: "/",
}
);
}
navigate(`/vhc-portal/quickconsultation/condition`);
},
onError: (error: Error) => {
const message =
(error as AxiosError<{ message?: string }>)?.response?.data
?.message ||
error.message ||
"Something went wrong!";

Toast(message, "error");
},
});
};

const handleUpdateConsultationAPI = (payload: any) => {
updateConsultation(payload, {
onSuccess: (data) => {
reset(defaultQuickConsultationValues);
const patientSlug = data?.patient_slug_id;
if (patientSlug) {
cookiesManager.set(
QUICK_CONSULTATION_DETAILS.PATIENT_SLUG,
patientSlug,
{
path: "/",
}
);
}
navigate(`/vhc-portal/quickconsultation/condition`);
},
onError: (error: Error) => {
const message =
(error as AxiosError<{ message?: string }>)?.response?.data
?.message ||
error.message ||
"Something went wrong!";

Toast(message, "error");
},
});
};

return (
<>
<div css={[padding(4, "x")]}>
<HeaderBack title="Quick Consultation" />
</div>

<FormProvider {...methods}>
<form
css={[margin(20, "bottom")]}
onSubmit={handleSubmit(submitQuickConsultation, (formErrors) => {
console.error("Validation failed", formErrors);
})}
>
<QuickConsultationForm
control={control}
errors={errors}
isFormDisabled={isFormDisabled}
patientProfileList={patientProfileList?.patient_profile_details}
setSelectedPatient={setSelectedPatient}
setDependentSlug={setDependentSlug}
reset={reset}
/>

<div
css={[
flex("row", "justify-between"),
gap(2),
padding(3),
background("white"),
css({
position: "fixed",
bottom: 0,
left: 0,
right: 0,
zIndex: 10,
}),
border(2, "gray-100"),
screen(
"md",
css({
position: "static",
zIndex: "auto",
}),
border(0),
margin(5, "x")
),
]}
>
{!isPhone && (
<Button type="button" variant="secondary" onClick={handleReset}>
Reset
</Button>
)}

<Button
type="submit"
css={[{ flex: 1 }, screen("md", { flex: 0 })]}
>
Confirm
</Button>
</div>
</form>
</FormProvider>

{isLoading && (
<div
css={[
flex("center"),
padding(5),
{
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
zIndex: 1000,
},
]}
>
<LoadingScreen />
</div>
)}
</>
);
}


Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation