"use client";

import React, { useContext, useEffect, useRef, useState } from "react";
import { BottomSheet } from "react-spring-bottom-sheet";
import Input from "plugins/Input/page";
import AppContext from "@ctx/AppContext";
import SimpleReactValidator from "simple-react-validator";
import CheckBoxBriz from "plugins/CheckBoxBriz/page";
import Buttonbriz from "plugins/Buttonbriz/page";
import { toast } from "react-toastify";

const BottomSheetAddUserToPositionShiftPlan = ({
  setUserAndPositionIds,
  userAndPositionIds,
  positionId,
  positionName,
  usersData,
}) => {
  const CTX = useContext(AppContext);

  const [, forceUpdate] = useState();

  const validator = useRef(
    new SimpleReactValidator({
      messages: {
        required: "پر کردن این فیلد الزامی میباشد",
      },
      element: (message) => (
        <>
          <div className="text-right px-1 ">
            <small className="text-red-600 t-ig-small  ">{message}</small>
          </div>
        </>
      ),
    })
  );

  return (
    <BottomSheet
      open={CTX.state.BottomSheetAddUserToPositionShiftPlanOpen}
      onDismiss={() => CTX.setBottomSheetAddUserToPositionShiftPlanOpen(false)}
      blocking={false}
    >
      <div className="text-center py-2 bg-secondary-950  ">
        <p className="mb-0 text-primary-300 relative top-[-5px]">
          افزودن یوزر به پوزیشن {positionName}
        </p>
      </div>

      {usersData?.map((e) => (
        <div
          className={`rounded-2xl m-3 tr03 ${
            userAndPositionIds?.find(
              (item) => item.value === e.userId && item.key == positionId
            )
              ? "bg-primary-100"
              : "bg-gray-100"
          }`}
          onClick={() => {
            const userExistsIndex = userAndPositionIds?.findIndex(
              (item) => item.value === e.userId && item.key === positionId
            );

            if (!userAndPositionIds || userExistsIndex === -1) {
              setUserAndPositionIds((current) => [
                ...(current || []),
                {
                  key: positionId,
                  value: e.userId,
                },
              ]);
            } else {
              setUserAndPositionIds((current) => [
                ...(current ? current.slice(0, userExistsIndex) : []),
                ...(current ? current.slice(userExistsIndex + 1) : []),
              ]);
            }
            CTX.setBottomSheetAddUserToPositionShiftPlanOpen(false);
          }}
        >
          <div className="flex rtl justify-between p-1">
            <p className="mb-0 m-1 text-sm">
              {e?.firstName} {e?.lastName}
            </p>

            <p className="mb-0  text-secondary-700 pl-4 rounded-full   text-sm">
              {e?.roleNames[0]}
            </p>
          </div>
        </div>
      ))}
    </BottomSheet>
  );
};

export default BottomSheetAddUserToPositionShiftPlan;
