"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-primary-300  ">
        <p className="mb-0 text-white 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 (userExistsIndex !== -1) {
              setUserAndPositionIds((current) => [
                ...(current ? current?.slice(0, userExistsIndex) : []),
                ...(current ? current?.slice(userExistsIndex + 1) : []),
              ]);
            } else {
              setUserAndPositionIds((current) => [
                ...current,
                {
                  key: positionId,
                  value: e?.userId,
                },
              ]);
            }
          }}
        >
          <div className="flex rtl justify-between p-3">
            <p className="mb-0 m-1">
              {e?.firstName} {e?.lastName}
            </p>

            <p className="mb-0 bg-primary-100 text-primary-300 rounded-full p-2  text-sm">
              {e?.roleNames[0]}
            </p>
          </div>
        </div>
      ))}
    </BottomSheet>
  );
};

export default BottomSheetAddUserToPositionShiftPlan;
