import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";
import axios from "axios";
import React, { useContext, useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { Link } from "react-router-dom";
import { UserContext } from "../../../Context/UserContextAPI";
import FingerprintMatch from "../../../components/Fingerprint/FingerprintMatch";
import AgencySummaryModal from "../../../components/Modal/RegistrationSummaryModal/AgencySummaryModal";
import CountrySummaryModal from "../../../components/Modal/RegistrationSummaryModal/CountrySummaryModal";
import PackageSummaryModal from "../../../components/Modal/RegistrationSummaryModal/PackageSummaryModal";
import RepresentativeSummeryModal from "../../../components/Modal/RegistrationSummaryModal/RepresentativeSummaryModal";
import { commonUserListColumns } from "../../../components/Table/CommonColumnsForUserList";
import UserListReportSummary from "../../../components/Users/UserListReportSummary";
import { calculateUserMedicalStatus } from "../../../components/Users/calculateUserMedicalStatus";
import { useFetchPatientsData } from "../../../hooks/useFetchPatientData";
import useIsOneIntroducer from "../../../hooks/useIsOneIntroducer";
import Loading from "../../../utils/Loader/Loading";
import UserSearchForm from "./../../../components/Users/UserSearchForm";
import MedicalReportMultipleSelect from "./MedicalReportsTableMultipleSelect";
import "./MedicalReports.scss";
const bioChemistryUrl = process.env.REACT_APP_BIOCHEMISTRY_URL;
const photoUrl = process.env.REACT_APP_PHOTO_URL;

const MedicalReportsCopy = ({ roleId, userId }) => {
  const { smsAPI, accessPerm } = useContext(UserContext);
  // const [usersData, setUsersData] = useState([]);
  const [rowSelection, setRowSelection] = useState([]);
  const [checkedUsers, setCheckedUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  // const [countryWiseUsers, setCountryWiseUsers] = useState([]);
  // const [introducerWiseUsers, setIntroducerWiseUsers] = useState([]);
  // const [packageWiseUsers, setPackageWiseUsers] = useState([]);
  // const [representativeWiseUsers, setRepresentativeWiseUsers] = useState([]);

  // get specific date users by tanstack query
  const [filterData, setFilterData] = useState({
    fromDate: new Date().toISOString().split("T")[0],
    toDate: new Date().toISOString().split("T")[0],
  });

  const { data, isFetching, isLoading } = useFetchPatientsData(filterData, {
    refetchInterval: 1000 * 30, // Refetch every 30 seconds
  });
  const usersData = data?.users || [];
  const countryWiseUsers = data?.countryWiseUser || [];
  const packageWiseUsers = data?.packageWiseUser || [];
  const introducerWiseUsers = data?.introducerWiseUser || [];
  const representativeWiseUsers = data?.representativeWiseUser || [];

  const getStatusColor = (status) => {
    switch (status) {
      case 2:
        return "text-success";
      case 3:
        return "text-danger";
      case 4:
        return "text-primary";
      default:
        return "";
    }
  };

  // custom hooks
  const isOneIntroducer = useIsOneIntroducer();

  const columnHelper = createColumnHelper();

  const commonColumns = useMemo(() => {
    // Move the column filtering logic to a separate function for clarity
    const filterColumns = (columns) =>
      columns.filter(
        (item) => item && (isOneIntroducer ? item.id !== "agency" : true)
      );

    // Apply the filter to the common columns
    return filterColumns(
      commonUserListColumns(usersData, {
        fromMedicalReports: accessPerm(33, 29),
      })
    );
  }, [usersData]);

  const getUniqueUserCollections = (collections) => {
    const seenGroupIds = new Set();
    let track = false;
    const result = [];

    for (const item of collections || []) {
      const categoryId = item.investigation_category_id;

      if (track && (categoryId === 4 || categoryId === 5)) continue;
      if (categoryId === 4 || categoryId === 5) track = true;

      const groupId = item.investigation_category?.investigation_group_id;
      if (!seenGroupIds.has(groupId)) {
        seenGroupIds.add(groupId);
        result.push(item);
      }
    }

    return result;
  };

  const isOnlyVaccine = (collection) => {
    const uniqueCollection = [...new Set(collection)];
    return uniqueCollection.length === 1 && uniqueCollection.includes(4);
  };

  const columns = useMemo(
    () => [
      ...commonColumns,

      // Conditionally render the Actions column
      ...(roleId !== 8
        ? [
            columnHelper.accessor("actions", {
              header: () => (
                <span className="d-flex justify-content-center">Actions</span>
              ),
              cell: ({ row }) => {
                const rowData = row.original;
                let unique = [];
                let track = false;
                const reversedIndex = usersData.length - row.index - 1;

                const collection = rowData?.user_collections?.map(
                  (collection) =>
                    collection.investigation_category?.investigation_group_id
                );
                const uniqueCollection = [...new Set(collection)].filter(
                  (item) => item !== 4
                );

                for (let i = 0; i < rowData.user_collections?.length; i++) {
                  if (
                    track &&
                    (rowData.user_collections[i].investigation_category_id ===
                      4 ||
                      rowData.user_collections[i].investigation_category_id ===
                        5)
                  )
                    continue;
                  if (
                    rowData.user_collections[i].investigation_category_id ===
                      4 ||
                    rowData.user_collections[i].investigation_category_id === 5
                  ) {
                    track = true;
                  }
                  unique.push(rowData.user_collections[i]);
                }

                const isPathologyDone = rowData?.is_pathology_done;
                const isPhysicalDone = rowData?.is_physical_done;
                const isRadiologyDone = rowData?.is_radiology_done;
                const isVaccineDone = rowData?.is_vaccine_done;
                const xrayUploaded =
                  rowData?.radiology_tests?.length > 0
                    ? rowData?.radiology_tests[0]?.user_file
                    : null;

                const uniqueNew = unique.reduce((acc, current) => {
                  const x = acc.find(
                    (item) =>
                      item.investigation_category.investigation_group_id ===
                      current.investigation_category.investigation_group_id
                  );
                  if (!x) {
                    acc.push(current);
                  }
                  return acc;
                }, []);

                return (
                  <div className="d-grid gap-1 d-grid-iocns">
                    {unique?.length > 0 && accessPerm(33, 5) && (
                      <div className="">
                        <Link
                          to={`/dashboard/medical-report/${rowData.id}`}
                          className={`action-icon ${getStatusColor(
                            rowData.status
                          )}`}
                          target="_blank"
                        >
                          <i
                            className={`fa-solid fa-eye fs-6 ${getStatusColor(
                              rowData.status
                            )}`}
                            data-bs-toggle="tooltip"
                            data-bs-placement="top"
                            title="Preview"
                          ></i>
                        </Link>
                      </div>
                    )}
                    {uniqueNew?.map(
                      (
                        { investigation_category: { investigation_group_id } },
                        i
                      ) => {
                        switch (investigation_group_id) {
                          case 1:
                            return (
                              accessPerm(33, 14) && (
                                <Link
                                  to={{
                                    pathname:
                                      isPathologyDone === 1 &&
                                      accessPerm(33, 11)
                                        ? `/dashboard/medical-reports/pathology/create/${rowData.id}`
                                        : isPathologyDone !== 1
                                        ? `/dashboard/medical-reports/pathology/create/${rowData.id}`
                                        : "",
                                    search: "?data=1",
                                  }}
                                  key={i}
                                  className={`action-icon pathology-icon`}
                                  style={{
                                    cursor:
                                      isPathologyDone === 1 &&
                                      !accessPerm(33, 11)
                                        ? "not-allowed"
                                        : "pointer",
                                    padding: "0",
                                    width: "0",
                                  }}
                                  target="_blank"
                                  onClick={(event) => {
                                    if (
                                      isPathologyDone === 1 &&
                                      !accessPerm(33, 11)
                                    ) {
                                      event.preventDefault();
                                    }
                                  }}
                                >
                                  <i
                                    className={`fa-solid fa-vial fs-6 ${
                                      isPathologyDone === 1
                                        ? "text-success"
                                        : ""
                                    }`}
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Pathology"
                                  ></i>
                                </Link>
                              )
                            );
                          case 2:
                            return (
                              accessPerm(33, 13) && (
                                <Link
                                  to={{
                                    pathname:
                                      isRadiologyDone === 1 &&
                                      accessPerm(33, 11)
                                        ? `/dashboard/medical-reports/radiology/create/${rowData.id}`
                                        : isRadiologyDone !== 1
                                        ? `/dashboard/medical-reports/radiology/create/${rowData.id}`
                                        : "",
                                    search: "?data=2",
                                  }}
                                  key={i}
                                  className={`action-icon radiology-icon`}
                                  style={{
                                    cursor:
                                      isRadiologyDone === 1 && xrayUploaded
                                        ? "not-allowed"
                                        : "pointer",
                                    padding: "0",
                                    width: "0",
                                  }}
                                  target="_blank"
                                  onClick={(event) => {
                                    if (
                                      isRadiologyDone === 1 &&
                                      !accessPerm(33, 11)
                                    ) {
                                      event.preventDefault();
                                    }
                                  }}
                                >
                                  <i
                                    className={`fa-solid fa-x-ray fs-6 ${
                                      isRadiologyDone === 1 && xrayUploaded
                                        ? "text-success"
                                        : isRadiologyDone === 0 && xrayUploaded
                                        ? "text-warning"
                                        : isRadiologyDone === 0 && !xrayUploaded
                                        ? "text-dark"
                                        : "text-success"
                                    }`}
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Radiology"
                                  ></i>
                                </Link>
                              )
                            );
                          case 3:
                            return (
                              accessPerm(33, 15) && (
                                <Link
                                  key={i}
                                  to={{
                                    pathname:
                                      isPhysicalDone === 1 && accessPerm(33, 11)
                                        ? `/dashboard/medical-reports/physical/create/${rowData.id}`
                                        : isPhysicalDone !== 1
                                        ? `/dashboard/medical-reports/physical/create/${rowData.id}`
                                        : "",
                                    search: "?data=3",
                                  }}
                                  className={`action-icon physical-icon`}
                                  style={{
                                    cursor:
                                      isPhysicalDone === 1 &&
                                      !accessPerm(33, 11)
                                        ? "not-allowed"
                                        : "pointer",
                                    padding: "0",
                                    width: "0",
                                  }}
                                  target="_blank"
                                  onClick={(event) => {
                                    if (
                                      isPhysicalDone === 1 &&
                                      !accessPerm(33, 11)
                                    ) {
                                      event.preventDefault();
                                    }
                                  }}
                                >
                                  <i
                                    className={`fa-solid fa-street-view fs-6 ${
                                      isPhysicalDone === 1 ? "text-success" : ""
                                    }`}
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Physical"
                                  ></i>
                                </Link>
                              )
                            );

                          case 4:
                            return (
                              accessPerm(33, 30) && (
                                <Link
                                  key={i}
                                  to={{
                                    pathname:
                                      isVaccineDone === 1 && accessPerm(33, 11)
                                        ? `/dashboard/medical-reports/vaccine/create/${rowData.id}`
                                        : isVaccineDone !== 1
                                        ? `/dashboard/medical-reports/vaccine/create/${rowData.id}`
                                        : "",
                                    search: "?data=4",
                                  }}
                                  className={`action-icon vaccine-icon`}
                                  style={{
                                    cursor:
                                      isVaccineDone === 1 && !accessPerm(33, 11)
                                        ? "not-allowed"
                                        : "pointer",
                                    padding: "0",
                                    width: "0",
                                  }}
                                  target="_blank"
                                  onClick={(event) => {
                                    if (
                                      isVaccineDone === 1 &&
                                      !accessPerm(33, 30)
                                    ) {
                                      event.preventDefault();
                                    }
                                  }}
                                >
                                  <i
                                    className={`fa-solid fa-syringe fs-6 ${
                                      isVaccineDone === 1
                                        ? "text-success"
                                        : "text-dark"
                                    }`}
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Vaccine"
                                  ></i>
                                </Link>
                              )
                            );
                          default:
                            return null;
                        }
                      }
                    )}
                    {/* Add other actions based on status */}
                    {accessPerm(33, 10) &&
                      (rowData.status === 2 &&
                      ((uniqueCollection?.length < 2 &&
                        (isPathologyDone ||
                          isPhysicalDone ||
                          isRadiologyDone)) ||
                        (uniqueCollection?.length >= 2 &&
                          uniqueCollection?.length < 3 &&
                          (isPathologyDone ? 1 : 0) +
                            (isPhysicalDone ? 1 : 0) +
                            (isRadiologyDone ? 1 : 0) >=
                            2) ||
                        (uniqueCollection?.length >= 3 &&
                          isPathologyDone &&
                          isPhysicalDone &&
                          isRadiologyDone)) ? (
                        <Link
                          to={`/dashboard/healthcard/${rowData.id}`}
                          className="action-icon prescription-icon"
                          state={rowData}
                          style={{
                            cursor: "pointer",
                            padding: "0",
                            width: "0",
                          }}
                          target="_blank"
                        >
                          <i
                            className="fa-regular fa-address-card fs-6 text-success"
                            data-bs-toggle="tooltip"
                            data-bs-placement="top"
                            title="Health Card"
                          ></i>
                        </Link>
                      ) : null)}
                    {rowData.status === 4 &&
                    ((uniqueCollection?.length < 2 &&
                      (isPathologyDone || isPhysicalDone || isRadiologyDone)) ||
                      (uniqueCollection?.length >= 2 &&
                        uniqueCollection?.length < 3 &&
                        (isPathologyDone ? 1 : 0) +
                          (isPhysicalDone ? 1 : 0) +
                          (isRadiologyDone ? 1 : 0) >=
                          2) ||
                      (uniqueCollection?.length >= 3 &&
                        isPathologyDone &&
                        isPhysicalDone &&
                        isRadiologyDone)) ? (
                      <>
                        {accessPerm(33, 12) && (
                          <Link
                            to={
                              rowData?.user?.user_pescriptions[0]?.user_id &&
                              accessPerm(33, 11)
                                ? `/dashboard/prescription/${rowData.id}`
                                : !rowData?.user?.user_pescriptions[0]?.user_id
                                ? `/dashboard/prescription/${rowData.id}`
                                : ""
                            }
                            className={`action-icon prescription-icon`}
                            style={{
                              cursor:
                                rowData?.user?.user_pescriptions[0]?.user_id &&
                                !accessPerm(33, 11)
                                  ? "not-allowed"
                                  : "pointer",
                              padding: "2px",
                              width: "0",
                              color: rowData?.user?.user_pescriptions[0]
                                ?.user_id
                                ? "#5cb85c"
                                : "#000",
                            }}
                            target="_blank"
                            onClick={(event) => {
                              if (
                                rowData?.user?.user_pescriptions[0]?.user_id &&
                                !accessPerm(33, 11)
                              ) {
                                event.preventDefault();
                              }
                            }}
                          >
                            <i
                              className="fa-solid fa-prescription"
                              data-bs-toggle="tooltip"
                              data-bs-placement="top"
                              title="Prescription"
                            ></i>
                          </Link>
                        )}
                        {accessPerm(33, 16) && (
                          <Link
                            to={`/dashboard/held-up-certificate/${rowData.id}`}
                            className="action-icon prescription-icon text-primary"
                            style={{
                              cursor: "pointer",
                              padding: "0",
                              width: "0",
                            }}
                            target="_blank"
                          >
                            <i
                              className="bi bi-patch-exclamation-fill fs-6"
                              data-bs-toggle="tooltip"
                              data-bs-placement="top"
                              title="Held Up Certificate"
                            ></i>
                          </Link>
                        )}
                      </>
                    ) : null}
                    {accessPerm(33, 16) &&
                      (rowData.status === 2 &&
                      ((uniqueCollection?.length < 2 &&
                        (isPathologyDone ||
                          isPhysicalDone ||
                          isRadiologyDone)) ||
                        (uniqueCollection?.length >= 2 &&
                          uniqueCollection?.length < 3 &&
                          (isPathologyDone ? 1 : 0) +
                            (isPhysicalDone ? 1 : 0) +
                            (isRadiologyDone ? 1 : 0) >=
                            2) ||
                        (uniqueCollection?.length >= 3 &&
                          isPathologyDone &&
                          isPhysicalDone &&
                          isRadiologyDone)) ? (
                        <Link
                          to={`/dashboard/fit-certificate/${rowData.id}`}
                          className="action-icon prescription-icon text-success"
                          style={{
                            cursor: "pointer",
                            padding: "0",
                            width: "0",
                          }}
                          target="_blank"
                        >
                          <i
                            className="bi bi-file-medical fs-6"
                            data-bs-toggle="tooltip"
                            data-bs-placement="top"
                            title="Fit Certificate"
                          ></i>
                        </Link>
                      ) : null)}
                    {accessPerm(33, 16) &&
                      (rowData.status === 3 &&
                      ((uniqueCollection?.length < 2 &&
                        (isPathologyDone ||
                          isPhysicalDone ||
                          isRadiologyDone)) ||
                        (uniqueCollection?.length >= 2 &&
                          uniqueCollection?.length < 3 &&
                          (isPathologyDone ? 1 : 0) +
                            (isPhysicalDone ? 1 : 0) +
                            (isRadiologyDone ? 1 : 0) >=
                            2) ||
                        (uniqueCollection?.length >= 3 &&
                          isPathologyDone &&
                          isPhysicalDone &&
                          isRadiologyDone)) ? (
                        <Link
                          to={`/dashboard/unfit-certificate/${rowData.id}`}
                          className="action-icon prescription-icon text-danger"
                          style={{
                            cursor: "pointer",
                            padding: "0",
                            width: "0",
                          }}
                          target="_blank"
                        >
                          <i
                            className="fa-regular fa-file-lines fs-6"
                            data-bs-toggle="tooltip"
                            data-bs-placement="top"
                            title="Unfit Certificate"
                          ></i>
                        </Link>
                      ) : null)}

                    {/* vaccine certificate */}

                    {accessPerm(33, 30) &&
                    isOnlyVaccine(collection) &&
                    isVaccineDone ? (
                      <Link
                        to={`/medical-vaccine-print/${rowData.id}`}
                        className="action-icon prescription-icon text-success"
                        style={{
                          cursor: "pointer",
                          padding: "0",
                          width: "0",
                        }}
                        target="_blank"
                      >
                        <i
                          className="bi bi-file-medical fs-6"
                          data-bs-toggle="tooltip"
                          data-bs-placement="top"
                          title="Vaccine Certificate"
                        ></i>
                      </Link>
                    ) : null}

                    <Link
                      to={`/dashboard/entry/${rowData.id}`}
                      className="action-icon prescription-icon text-dark"
                      state={rowData}
                      style={{
                        cursor: "pointer",
                        padding: "0",
                        width: "0",
                      }}
                      target="_blank"
                    >
                      <i
                        className={`bi bi-card-text fs-6 ${
                          isRadiologyDone === 1 && xrayUploaded
                            ? "text-success"
                            : isRadiologyDone === 0 && xrayUploaded
                            ? "text-warning"
                            : isRadiologyDone === 0 && !xrayUploaded
                            ? "text-dark"
                            : "text-success"
                        }`}
                        data-bs-toggle="tooltip"
                        data-bs-placement="top"
                        title="Physical Pathology X-Ray"
                      ></i>
                    </Link>
                  </div>
                );
              },
            }),
          ]
        : []), // If roleid is 8, return an empty array
    ],
    [accessPerm, usersData]
  );

  const table = useReactTable({
    data: usersData,
    columns: columns,
    getCoreRowModel: getCoreRowModel(),
    state: {
      rowSelection: rowSelection,
    },
    onRowSelectionChange: setRowSelection,
    enableRowSelection: true,
  });

  const handlerSms = async (e) => {
    const sendSms = e.target.sms.value;

    e.preventDefault();
    const representativeCounts = new Map();

    const introducerUsersMap = {};
    const promises = [];

    //send notification
    axios
      .post(`${process.env.REACT_APP_API_BASE_URL}/checked-notifications`, {
        checkedData: checkedUsers,
      })
      .then()
      .catch((error) => console.log(error));

    for (const checkedUser of checkedUsers) {
      const introducerMobile = checkedUser?.introducer_user?.mobile;

      if (introducerMobile) {
        if (!introducerUsersMap[introducerMobile]) {
          introducerUsersMap[introducerMobile] = [];
        }

        introducerUsersMap[introducerMobile].push(checkedUser);
      }
    }

    //first sms from first or second option to client or introducer and introducer
    for (const checkedUser of checkedUsers) {
      let recipientMobile;
      if (sendSms === "1") {
        if (checkedUser?.introducer_user?.SMSChecked === 0) {
          recipientMobile =
            checkedUser?.user?.mobile || checkedUser?.introducer_user?.mobile;
        } else {
          recipientMobile = checkedUser?.user?.mobile;
        }
      } else if (
        sendSms === "2" &&
        checkedUser?.introducer_user?.SMSChecked === 0
      ) {
        recipientMobile = checkedUser?.introducer_user?.mobile;
      }
      if (recipientMobile) {
        const verificationURL = `https://${process.env.REACT_APP_API_BASE_URL}:5005/medical-verification/result/report/print/${checkedUser?.user_id}`;
        const status = getStatusString(checkedUser?.user?.status);
        const clientName = `${checkedUser?.user?.f_name}`;
        const clientMessage = `Medical result of ${
          checkedUser?.user?.reg_prefix || ""
        }${checkedUser?.user?.registration_no} - ${clientName} for ${
          checkedUser?.country?.name
        } is ${status} Check here: ${verificationURL}.`;

        // Push the promise into the promises array
        promises.push(
          smsAPI(recipientMobile, clientMessage)
            .then((res) => {
              console.log("SMS sent to", recipientMobile, res);
            })
            .catch((err) => {
              console.log("Error sending SMS to", recipientMobile, err);
            })
        );
      }
    }
    //fix
    //second sms from second option to introducer
    for (const [introducerMobile, introducerCheckedUsers] of Object.entries(
      introducerUsersMap
    )) {
      const introducerFitCount = introducerCheckedUsers.filter(
        (user) => user?.user?.status === 2
      ).length;
      const introducerUnfitCount = introducerCheckedUsers.filter(
        (user) => user?.user?.status === 3
      ).length;
      const introducerHeldUpCount = introducerCheckedUsers.filter(
        (user) => user?.user?.status === 4
      ).length;

      const smsChecked = introducerCheckedUsers[0]?.introducer_user?.SMSChecked;
      // Create SMS message
      if (smsChecked === 0) {
        const statusCountsString = `Fit: ${introducerFitCount}, Unfit: ${introducerUnfitCount}, Held Up: ${introducerHeldUpCount}`;
        const introducerName = `${introducerCheckedUsers[0]?.introducer_user?.f_name}`;
        const message = `Introducer - ${introducerName} has patients who are ${statusCountsString}.`;

        // Send SMS to introducer
        const verificationURL = `https://${process.env.REACT_APP_API_BASE_URL}:5005/medical-verification/result/report/print/${introducerCheckedUsers[0]?.user_id}`;
        const introducerStatus = getStatusString(
          introducerCheckedUsers[0]?.user?.status
        );
        const introducerClientName = `${introducerCheckedUsers[0]?.user?.f_name}`;
        const introducerClientMessage = `Medical result of  ${
          introducerCheckedUsers[0]?.user?.reg_prefix || ""
        }${
          introducerCheckedUsers[0]?.user?.registration_no
        } - ${introducerClientName} for ${
          introducerCheckedUsers[0]?.country?.name
        } is ${introducerStatus}. Please click the link ${verificationURL} to show your medical result.  Thank You! ${verificationURL}. ${message}`;

        promises.push(
          smsAPI(introducerMobile, introducerClientMessage)
            .then((res) => {
              console.log("SMS sent to", introducerMobile, res);
            })
            .catch((err) => {
              console.log("Error sending SMS to", introducerMobile, err);
            })
        );
      }
    }

    //third sms from second option to representative
    // for (const checkedUser of checkedUsers) {
    //   const representativeMobile =
    //     checkedUser?.introducer_user?.user_users_maps?.map(
    //       (user) => user?.representative_user_map?.mobile
    //     )[0];

    //   if (representativeMobile) {
    //     const representativeStatusCounts = representativeCounts.get(
    //       representativeMobile
    //     ) || {
    //       fit: 0,
    //       unfit: 0,
    //       heldUp: 0,
    //     };

    //     const userStatus = checkedUser?.user?.status;
    //     if (userStatus === 2) {
    //       representativeStatusCounts.fit++;
    //     } else if (userStatus === 3) {
    //       representativeStatusCounts.unfit++;
    //     } else if (userStatus === 4) {
    //       representativeStatusCounts.heldUp++;
    //     }

    //     representativeCounts.set(
    //       representativeMobile,
    //       representativeStatusCounts
    //     );
    //   }
    // }

    // Iterate through the representativeCounts and send SMS
    // for (const [representativeMobile, statusCounts] of representativeCounts) {
    //   const verificationURL = `https://${process.env.REACT_APP_API_BASE_URL}:5005/medical-verification/result/report/print/${representativeMobile}`;
    //   const statusCountsString = `Fit: ${statusCounts.fit}, Unfit: ${statusCounts.unfit}, Held Up: ${statusCounts.heldUp}`;
    //   const representativeMessage = `Your patients have status counts - ${statusCountsString}. Check here: ${verificationURL}.`;

    //   // Push the promise into the promises array
    //   promises.push(
    //     smsAPI(representativeMobile, representativeMessage)
    //       .then((res) => {
    //         console.log(
    //           "SMS sent to representative",
    //           representativeMobile,
    //           res
    //         );
    //       })
    //       .catch((err) => {
    //         console.log(
    //           "Error sending SMS to representative",
    //           representativeMobile,
    //           err
    //         );
    //       })
    //   );
    // }

    // Wait for all the promises to resolve
    try {
      await Promise.all(promises);
      toast.success("SMS sent successfully!");
    } catch (error) {
      toast.error("Failed to send some SMS messages");
    }
  };

  const getStatusString = (status) => {
    switch (status) {
      case 2:
        return "FIT";
      case 3:
        return "UNFIT";
      case 4:
        return "HELD-UP";
      default:
        return "PROCESSING";
    }
  };

  useEffect(() => {
    const selectedRows = table
      .getSelectedRowModel()
      ?.flatRows?.map((row) => row.original);
    setCheckedUsers(selectedRows);
  }, [table.getSelectedRowModel()]);

  // get users data
  // useEffect(() => {
  //   (async () => {
  //     try {
  //       await methodFilterPatientsDetails({
  //         fromDate: new Date(),
  //         toDate: new Date(),
  //       });
  //       // console.log(response);
  //     } catch (error) {
  //       console.log(error);
  //     }
  //   })();
  //   return () => {
  //     // console.log("unmount");
  //   };
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, []);

  // radiology page redirect with fingerprint search
  function handleFingerPrintRadiologySearch(user) {
    return window.open(
      `/dashboard/medical-reports/radiology/${user?.userId}?data=2`,
      "_blank"
    );
  }

  // vaccine page redirect with fingerprint search

  function handleFingerPrintVaccineSearch(user) {
    return window.open(
      `/dashboard/medical-reports/vaccine/create/${user?.userId}?data=4`,
      "_blank"
    );
  }

  // physical page redirect with fingerprint search
  function handleFingerPrintPhysicalSearch(user) {
    return window.open(
      `/dashboard/medical-reports/physical/${user?.userId}?data=3`,
      "_blank"
    );
  }
  // console.log("userDetails", usersData);

  const fingeprintUserData = useMemo(() => {
    return usersData?.reduce((users, user) => {
      if (user?.finger_print_temp) {
        users.push({
          userId: user?.id,
          finger_print_temp: user?.finger_print_temp,
        });
      }
      return users;
    }, []);
  }, [usersData]);

  return (
    <>
      <div className="card medical-report-container">
        <div className="card-body">
          <div className="rounded">
            <div className="card shadow-none mb-3">
              <div className="border p-3 rounded">
                <h6
                  className="mb-0 btn btn-danger text-white text-capitalize fw-bold m-0 p-0"
                  style={{ cursor: "default" }}
                >
                  Medical Reports
                </h6>
                <div className="">
                  <div className="d-flex flex-wrap">
                    <UserSearchForm
                      userSearchHandler={(val) => setFilterData(val)}
                      inlineButtonComponent={
                        <>
                          {accessPerm(33, 14) && (
                            <Link
                              to={bioChemistryUrl}
                              className="btn btn-success"
                              target="_blank"
                            >
                              Upload Bio-Chemistry
                            </Link>
                          )}
                          {accessPerm(33, 14) && (
                            <Link
                              to={photoUrl}
                              className="btn btn-info"
                              target="_blank"
                            >
                              Photo
                            </Link>
                          )}
                        </>
                      }
                    />
                    <div className="d-flex gap-3 ms-5">
                      {accessPerm(33, 13) && (
                        <FingerprintMatch
                          successHandler={handleFingerPrintRadiologySearch}
                          userData={fingeprintUserData}
                        >
                          <img
                            width={40}
                            height={40}
                            src="fingerprint.png"
                            alt="radiology"
                          />
                          <p>Radiology</p>
                        </FingerprintMatch>
                      )}

                      {accessPerm(33, 15) && (
                        <FingerprintMatch
                          successHandler={handleFingerPrintPhysicalSearch}
                          userData={fingeprintUserData}
                        >
                          <img
                            width={40}
                            height={40}
                            src="fingerprint.png"
                            alt="physical"
                          />
                          <p>Physical</p>
                        </FingerprintMatch>
                      )}

                      {accessPerm(33, 30) && (
                        <FingerprintMatch
                          successHandler={handleFingerPrintVaccineSearch}
                          userData={fingeprintUserData}
                        >
                          <img
                            width={40}
                            height={40}
                            src="fingerprint.png"
                            alt="radiology"
                          />
                          <p>Vaccine</p>
                        </FingerprintMatch>
                      )}
                    </div>
                  </div>

                  {accessPerm(33, 25) && roleId !== 8 && (
                    <div className="d-flex flex-wrap align-items-end gap-0 justify-content-center mt-2 w-100">
                      <form
                        className="d-flex align-items-center gap-2"
                        onSubmit={(e) => handlerSms(e)}
                        style={{ width: "450px" }}
                      >
                        <select
                          name="sms"
                          id="sms"
                          className="w-100 form-select"
                          defaultValue=""
                        >
                          <option value="">Select an Action</option>
                          <option value="1">Send SMS To Client</option>
                          <option value="2">Send SMS To Introducer</option>
                        </select>
                        <button type="submit" className="btn btn-warning">
                          Apply
                        </button>
                      </form>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* report button for multiple selected rows */}
            <MedicalReportMultipleSelect table={table} />

            {/* user report summary */}
            <UserListReportSummary userList={usersData} />

            {isFetching ? (
              <Loading />
            ) : (
              <table className="table align-middle table-hover table-bordered mb-0 rounded">
                <thead className="bg-primary">
                  {table.getHeaderGroups().map((headerGroup) => (
                    <tr key={headerGroup.id}>
                      {headerGroup.headers.map((header, i) => (
                        <th
                          key={i}
                          id={`th-${i}`}
                          className="text-light p-1"
                          style={{ backgroundColor: "#095d7e" }}
                        >
                          {header.isPlaceholder
                            ? null
                            : flexRender(
                                header.column.columnDef.header,
                                header.getContext()
                              )}
                        </th>
                      ))}
                    </tr>
                  ))}
                </thead>
                <tbody>
                  {table.getRowModel().rows.map((row, i) => {
                    // } = row;
                    const { isDone, status } = calculateUserMedicalStatus(
                      row?.original
                    );

                    return (
                      <tr
                        key={i}
                        className={`${
                          isDone && status === 4 && "text-primary"
                        } ${isDone && status === 2 && "text-success"} ${
                          isDone && status === 3 && "text-danger"
                        } ${status === 1 && "text-dark"} 
         `}
                      >
                        {row.getVisibleCells().map((cell, i) => (
                          <td key={i} className="p-1">
                            {flexRender(
                              cell.column.columnDef.cell,
                              cell.getContext()
                            )}
                          </td>
                        ))}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>

      {/* Registration Summery Modal Body */}
      <div>
        <CountrySummaryModal
          countryWiseUsers={countryWiseUsers}
          isColumn2={true}
        />
        <AgencySummaryModal
          introducerWiseUsers={introducerWiseUsers}
          isColumn2={true}
        />
        <PackageSummaryModal packageWiseUsers={packageWiseUsers} isColumn2 />
        <RepresentativeSummeryModal
          representativeWiseUsers={representativeWiseUsers}
          isColumn2={true}
        />
      </div>
    </>
  );
};

export default React.memo(MedicalReportsCopy);
