"use client";

import React, { useContext, 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 { toast } from "react-toastify";
import Buttonbriz from "plugins/Buttonbriz/page";

const BottomSheetCreateEmployees = (props) => {
  const CTX = useContext(AppContext);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [nationalId, setNationalId] = useState("");
  const [gender, setGender] = useState(0);
  const [roleSelectData, setRoleSelectData] = useState("");
  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>
        </>
      ),
    })
  );
  const rolesChoose = CTX.state.rolesChoose;
  const rolesData = CTX.state.rolesData;

  const body = {
    phoneNumber,
    firstName,
    lastName,
    // birthDate,
    gender,
    nationalId,
    roleIds: rolesChoose,
  };

  const handleCreateUser = () => {
    if (validator.current.allValid()) {
      CTX.CreateUser(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 deleteRole = (id) => {
    CTX.setRolesChoose(rolesChoose.filter((el) => el !== id));
  };

  return (
    <BottomSheet
      onSpringStart={(e) => {
        if (e.type == "OPEN") {
          CTX.GetRoles();
        }
      }}
      open={CTX.state.BottomSheetCreateEmployeesOpen}
      onDismiss={() => CTX.setBottomSheetCreateEmployeesOpen(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="firstName-id"
            name="firstName"
            type={"text"}
            value={firstName}
            inputEvent={(e) => {
              setFirstName(e.target.value);
              validator.current.showMessageFor("firstName");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "firstName",
              firstName,
              "required"
            )}
          />
        </div>

        <div>
          <Input
            lable="نام خانوادگی"
            id="lastName-id"
            name="lastName"
            type={"text"}
            value={lastName}
            inputEvent={(e) => {
              setLastName(e.target.value);
              validator.current.showMessageFor("lastName");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "lastName",
              lastName,
              "required"
            )}
          />
        </div>

        <div className="">
          <Input
            lable="جنسیت"
            id="gender-id"
            name="gender"
            type={"text"}
            value={gender}
            inputEvent={(e) => {
              setGender(e.target.value);
              validator.current.showMessageFor("gender");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "gender",
              gender,
              "required"
            )}
            select={true}
            selectData={[
              { key: "مرد", value: "0" },
              { key: "زن", value: "1" },
            ]}
          />
        </div>

        <div className="">
          <Input
            lable="شماره تماس"
            id="phoneNumber-id"
            name="phoneNumber"
            type={"text"}
            value={phoneNumber}
            inputEvent={(e) => {
              setPhoneNumber(e.target.value);
              validator.current.showMessageFor("phoneNumber");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "phoneNumber",
              phoneNumber,
              "required"
            )}
          />
        </div>

        <div className="">
          <Input
            lable="کد ملی"
            id="nationalId-id"
            name="nationalId"
            type={"text"}
            value={nationalId}
            inputEvent={(e) => {
              setNationalId(e.target.value);
            }}
            style="text-right"
          />
        </div>

        <div className="">
          <Input
            lable="سمت شغلی"
            id="roleIds-id"
            name="roleIds"
            type={"text"}
            value={roleSelectData}
            inputEvent={(e) => {
              setRoleSelectData(e.target.value);
              console.log("s11515", e.target.value);

              if (!!rolesChoose.find((b) => b == e.target.value)) {
                toast.error("نقش تکراری است", {
                  position: "bottom-right",
                  closeOnClick: true,
                });
              } else {
                CTX.setRolesChoose((current) => [...current, e.target.value]);
              }
            }}
            style="text-right"
            validatorData={validator.current.message(
              "phoneNumber",
              phoneNumber,
              "required"
            )}
            select={true}
            selectData={CTX.state.rolesData}
          />
        </div>

        <div className="flex flex-wrap mt-3 rtl">
          {rolesChoose &&
            rolesChoose.map((e) => (
              <div className="flex bg-gray-300 p-1 rounded-full m-1 justify-start">
                <div
                  className="w-[30px] h-[30px] rounded-full bg-gray-400 "
                  onClick={() => deleteRole(e)}
                ></div>

                <div>
                  <p className="mb-0 px-3 text-sm mt-1">
                    {rolesData?.find((b) => b.id == e).persianName}
                  </p>
                </div>
              </div>
            ))}
        </div>
        <Buttonbriz
          title="ثبت کاربر  "
          color="INFO"
          icon="CHECK"
          buttonEvent={() => handleCreateUser()}
        />
      </div>
    </BottomSheet>
  );
};

export default BottomSheetCreateEmployees;
