import {
Box,
Chip,
Dialog,
DialogContent,
DialogTitle,
IconButton,
MenuItem,
Select,
TextField,
Typography,
Button,
DialogActions,
} from "@mui/material";
import { useFormik } from "formik";
import React, { useMemo, useRef, useState } from "react";
import * as Yup from "yup";
import EditIcon from "@mui/icons-material/Edit";
import CloseIcon from "@mui/icons-material/Close";
import MultiSelect from "../../components/MultiSelect";
/* ----------------- Custom Imports ----------------- */
import PageHeader from "../../components/PageHeader";
import Table from "../../components/Table";
import { useStyles } from "./userStyles";
/* ----------------- Assets ----------------- */
import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/Delete";
/* ----------------- Utils ----------------- */
import { format } from "date-fns";
import { NOTIFICATION, NOT_AVAILABLE_TEXT } from "../../constants";
import { pushNotification } from "../../utils/notification";
import {
createDoctor,
deleteDoctor,
getClinicDoctors,
updateDoctor,
} from "../../services/clinics.service";
import { useSelector } from "react-redux";
/* ----------------- Validation Schema ----------------- */
const validationSchema = Yup.object().shape({
userName: Yup.string().required("User Name is required"),
userType: Yup.string().required("User Type is required"),
appointmentType: Yup.array().min(
1,
"At least one appointment type is required"
),
});
function Users() {
const ref = useRef(null);
const classes = useStyles();
const userTypes = [
{ id: "doctor", name: "Doctor" },
{ id: "nurse", name: "Nurse" },
];
/* ----------------- State Variables ----------------- */
const [deleteModal, setDeleteModal] = useState(false);
const [userTotalCount, setUserTotalCount] = useState(0);
const [dialogOpen, setDialogOpen] = useState(false);
const [isEditUser, setIsEditUser] = useState(false);
const [deleteId, setDeleteId] = useState(null);
// Fix: Use proper initial values for formik
const initialValues = {
userName: "",
userType: userTypes[0].id,
appointmentType: [],
appointmentTypeObject: {},
};
/* ----------------- Get Users ----------------- */
const getData = async (filters) => {
const resp = await getClinicDoctors(filters);
setUserTotalCount(resp?.data?.data?.total);
return { data: resp?.data?.data?.data, rowCount: resp?.data?.data?.total };
};
const handleDialog = () => {
if (dialogOpen) {
// Reset form when closing dialog
formik.resetForm();
setIsEditUser(false);
}
setDialogOpen(!dialogOpen);
};
const editUser = async (row) => {
const { id, name, role, appointmentTypes } = row.original;
// Set form values for editing
formik.setValues({
id,
userName: name || '',
userType: role || userTypes[0]?.id || '',
appointmentType: Array.isArray(appointmentTypes) ? appointmentTypes : [],
appointmentTypeObject: {}
});
setIsEditUser(true);
setDialogOpen(true);
};
const deleteUserToggle = (id) => {
setDeleteId(id);
setDeleteModal(!deleteModal);
};
/* ----------------- Handle Submit ----------------- */
const handleSubmit = async (values, { resetForm, setSubmitting }) => {
try {
const payload = {
name: values.userName,
role: values.userType,
appointmentTypes: values.appointmentType.map((type) => type.id),
};
let resp;
if (isEditUser) {
resp = await updateDoctor(payload, values.id);
} else {
resp = await createDoctor(payload);
}
if (resp?.data?.data?.error) {
pushNotification(resp?.data?.data?.error, NOTIFICATION.ERROR);
return;
}
pushNotification(
`${isEditUser ? "User updated" : "User added"} successfully`,
NOTIFICATION.SUCCESS
);
await ref.current?.reFetchData();
handleDialog();
resetForm();
setSubmitting(false);
} catch (error) {
console.log(error);
pushNotification("Failed to save user", NOTIFICATION.ERROR);
}
};
const handleDeleteUser = async () => {
try {
const resp = await deleteDoctor(deleteId);
if (resp?.data?.data?.error) {
pushNotification(resp?.data?.data?.error, NOTIFICATION.ERROR);
return;
}
pushNotification("User deleted successfully", NOTIFICATION.SUCCESS);
await ref.current?.reFetchData();
setDeleteModal(false);
} catch (error) {
console.log(error);
pushNotification("Failed to delete user", NOTIFICATION.ERROR);
}
};
/* ----------------- Formik Setup ----------------- */
const formik = useFormik({
initialValues,
validationSchema,
onSubmit: handleSubmit,
});
/* ----------------- Table Columns ----------------- */
const columns = useMemo(
() => [
{
size: 30,
header: "S.no.",
Cell: (props) => {
const tableState = props?.table?.getState();
const serialNumber = (
props?.row?.index +
1 +
tableState?.pagination?.pageIndex * tableState?.pagination?.pageSize
)
?.toString()
?.padStart(1, "0");
return {serialNumber};
},
enableSorting: false,
},
{
size: 100,
accessorFn: ({ name }) => name || NOT_AVAILABLE_TEXT,
accessorKey: "name",
header: "Doctor/Nurse Name",
isBold: true,
},
{
size: 100,
accessorFn: ({ role }) => (role ? role.charAt(0).toUpperCase() + role.slice(1) : NOT_AVAILABLE_TEXT),
accessorKey: "role",
header: "User Type",
},
{
size: 200,
accessorKey: "appointmentTypes",
header: "Appointment Types",
Cell: ({ row }) => {
const appointmentTypes = row?.original?.appointmentTypes;
const typesArray =
Array.isArray(appointmentTypes) && appointmentTypes.length > 0
? appointmentTypes
: typeof appointmentTypes === "string" &&
appointmentTypes.trim() !== ""
? appointmentTypes.split(",").map((type) => type.trim())
: [];
return (