"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,
}) => {
  const CTX = useContext(AppContext);

  const [, forceUpdate] = useState();

  const usersData = CTX.state.usersData;

  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>
        </>
      ),
    })
  );

  // const body = {
  //   persianName,
  //   englishName,
  //   description,
  //   permissions: permissionsChoose,
  // };
  // const bodyUpdate = {
  //   persianName,
  //   englishName,
  //   description,
  //   permissions: permissionsChoose,
  //   roleId: roleData.roleId,
  // };

  // const clear = () => {
  //   setPersianName("");
  //   setEnglishName("");
  //   setDescription("");
  //   CTX.setPermissionsChoose([]);
  // };

  // const handleCreateRole = (update) => {
  //   if (validator.current.allValid()) {
  //     if (update == "UPDATE") {
  //       CTX.UpdateRole(bodyUpdate);
  //     } else {
  //       CTX.CreateRole(body);
  //     }
  //   } else {
  //     toast.error("پرکردن همه ی فیلد ها واجب است", {
  //       position: "bottom-right",
  //       autoClose: 2000,
  //       hideProgressBar: false,
  //       closeOnClick: true,
  //       pauseOnHover: true,
  //       draggable: true,
  //       progress: undefined,
  //     });

  //     validator.current.showMessages();
  //     forceUpdate(1);
  //   }
  // };

  const handleBottomSheetAddUserToPositionShiftPlan = (e) => {
    if (e.type == "OPEN") {
      if (!!usersData.length <= 0) {
        // User data is not in state, send request to get user
        CTX.GetUsers();
      }
    } else if (e.type == "CLOSE") {
      // clear();
      // CTX.setGoToEditRole(false);
      // CTX.setIdEditRole(null);
      // CTX.setRoleData([]);
    }
  };

  // useEffect(() => {
  //   if (goToEditRole) {
  //     setPersianName(roleData.persianName);
  //     setEnglishName(roleData.englishName);
  //     setDescription(roleData.description);
  //     CTX.setPermissionsChoose(roleData.permissions);
  //   }
  // }, [roleData]);

  return (
    <BottomSheet
      onSpringStart={(e) => handleBottomSheetAddUserToPositionShiftPlan(e)}
      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.slice(0, userExistsIndex),
                ...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;
