"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 BottomSheetCreateRole = (props) => {
  const CTX = useContext(AppContext);
  const [persianName, setPersianName] = useState("");
  const [englishName, setEnglishName] = useState("");
  const [description, setDescription] = useState("");
  const [, forceUpdate] = useState();

  const permissionsData = CTX.state.permissions;
  const permissionsChoose = CTX.state.permissionsChoose;
  const goToEditRole = CTX.state.goToEditRole;
  const idEditRole = CTX.state.idEditRole;
  const roleData = CTX.state.roleData;

  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 handleBottomSheetCreateRole = (e) => {
    if (e.type == "OPEN") {
      CTX.GetPermissions();
      if (goToEditRole) {
        CTX.GetRole(idEditRole);
      }
    } 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) => handleBottomSheetCreateRole(e)}
      open={CTX.state.BottomSheetCreateRoleOpen}
      onDismiss={() => CTX.setBottomSheetCreateRoleOpen(false)}
      blocking={false}
    >
      <div className="text-center py-2 bg-primary-300  ">
        <p className="mb-0 text-white relative top-[-5px]">افزودن نقش جدید</p>
      </div>

      <div className="bg-body-100 p-4">
        <div className="">
          <Input
            lable=" (فارسی) نام نقش"
            id="persianName-id"
            name="persianName"
            type={"text"}
            value={persianName}
            inputEvent={(e) => {
              setPersianName(e.target.value);
              validator.current.showMessageFor("persianName");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "persianName",
              persianName,
              "required"
            )}
          />
        </div>

        <div className="">
          <Input
            lable=" (انگلیسی) نام نقش"
            id="englishName-id"
            name="englishName"
            type={"text"}
            value={englishName}
            inputEvent={(e) => {
              setEnglishName(e.target.value);
              validator.current.showMessageFor("englishName");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "englishName",
              englishName,
              "required"
            )}
          />
        </div>

        <div className="">
          <Input
            lable=" توضیحات"
            id="description-id"
            name="description"
            type={"text"}
            value={description}
            inputEvent={(e) => {
              setDescription(e.target.value);
              validator.current.showMessageFor("description");
            }}
            textarea={true}
            style="text-right"
          />
        </div>

        <div className="my-10">
          <div className="text-right m-2">
            <h4 className="text-base  font-bold text-primary-300">
              دسترسی های مورد نظر{" "}
            </h4>
          </div>

          {permissionsData &&
            permissionsData.map((e) => (
              <CheckBoxBriz
                title={e.title}
                detail={e.detail}
                value={e.value}
                checkBoxEvent={(e) => setRoleCheckBox(e.target.checked)}
              />
            ))}
        </div>

        {goToEditRole ? (
          <Buttonbriz
            title="ویرایش نقش"
            color="INFO"
            icon="CHECK"
            buttonEvent={() => handleCreateRole("UPDATE")}
            subButton={true}
            subButtonTitle="حذف نقش"
            subButtonEvent={() => CTX.DeleteRole(idEditRole)}
          />
        ) : (
          <Buttonbriz
            title="ثبت نقش"
            color="PRIMARY"
            icon="CHECK"
            buttonEvent={() => handleCreateRole()}
          />
        )}
      </div>
    </BottomSheet>
  );
};

export default BottomSheetCreateRole;
