"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 { toast } from "react-toastify";
import Buttonbriz from "plugins/Buttonbriz/page";
import DatePickerIran from "plugins/DatePickerIran/page";
import moment from "jalali-moment";
import validateIranPhone from "plugins/IranPhoneRegex";
const jalaliMoment = require("jalali-moment");

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(parseInt(0));
  // const [birthDate, setBirthDate] = useState(null);
  const [roleSelectCurrntData, setRoleSelectCurrntData] = useState("");
  const [roleSelectData, setRoleSelectData] = useState([]);

  // const [positionId, setPositionId] = useState("");
  const [positionIdSelectData, setPositionIdSelectData] = 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 goToEditUser = CTX.state.goToEditUser;
  const idEditUser = CTX.state.idEditUser;
  const userData = CTX.state.userData;
  const positionsData = CTX.state.positionsData;

  const body = {
    phoneNumber,
    firstName,
    lastName,
    // birthDateTimeStamp:
    //   birthDate &&
    //   moment
    //     .utc(
    //       [birthDate.year, birthDate.month, birthDate.day],
    //       "jYYYY-jMM-jDDTHH"
    //     )
    //     .unix(),
    gender: parseInt(gender),
    // nationalId,
    roleIds: rolesChoose,
    // positionId,
  };

  const bodyUpdate = {
    phoneNumber,
    firstName,
    lastName,
    // birthDateTimeStamp:
    //   birthDate &&
    //   moment
    //     .utc(
    //       [birthDate.year, birthDate.month, birthDate.day],
    //       "jYYYY-jMM-jDDTHH"
    //     )
    //     .unix(),
    gender: parseInt(gender),
    // nationalId,
    roleIds: rolesChoose,
    userId: userData.id,
    // positionId,
  };

  const clear = () => {
    setFirstName("");
    setLastName("");
    setPhoneNumber("");
    // setNationalId("");
    setGender(parseInt(0));
    // setBirthDate("");
    setRoleSelectCurrntData("");
    setRoleSelectData([]);
    // setPositionId("");
    CTX.setRolesChoose([]);
  };

  const handleCreateUser = (update) => {
    if (validateIranPhone(phoneNumber)) {
      if (validator.current.allValid()) {
        if (update == "UPDATE") {
          CTX.UpdateUser(bodyUpdate);
        } else {
          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);
      }
    } else {
      toast.error("شماره تماس را درست وارد کنید", {
        position: "bottom-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  const deleteRole = (id) => {
    CTX.setRolesChoose(rolesChoose.filter((el) => el !== id));
  };

  const handleBottomSheetCreateEmployeesOpen = (e) => {
    setRoleSelectData(
      rolesData.map((item) => ({
        key: item.persianName,
        value: item.id,
      }))
    );

    // setPositionIdSelectData(
    //   positionsData.map((item) => ({
    //     key: item.name,
    //     value: item.id,
    //   }))
    // );

    if (e.type == "OPEN") {
      CTX.GetRoles();
      if (goToEditUser) {
        CTX.GetUser(idEditUser);
      }
    } else if (e.type == "CLOSE") {
      clear();
      CTX.setGoToEditUser(false);
      CTX.setIdEditUser(null);
      CTX.setUserData([]);
    }
  };

  useEffect(() => {
    if (goToEditUser) {
      // const date = moment
      //   .unix(userData.birthDateTimeStamp)
      //   .locale("fa")
      //   .format("YYYY/MM/DD")
      //   .split("/");

      setFirstName(userData.firstName);
      setLastName(userData.lastName);
      setPhoneNumber(userData.phoneNumber);
      // setNationalId(userData.nationalId);
      setGender(userData.gender);
      // setBirthDate({
      //   day: parseInt(date[2]),
      //   month: parseInt(date[1]),
      //   year: parseInt(date[0]),
      // });
      // setRoleSelectCurrntData("");
      CTX.setRolesChoose(userData.roleIds);
      // setPositionId(userData.positionId);
    }
  }, [userData]);

  return (
    <BottomSheet
      onSpringStart={(e) => handleBottomSheetCreateEmployeesOpen(e)}
      open={CTX.state.BottomSheetCreateEmployeesOpen}
      onDismiss={() => CTX.setBottomSheetCreateEmployeesOpen(false)}
      blocking={true}
    >
      <div className="text-center py-2 bg-secondary-950  ">
        <p className="mb-0 text-primary-300 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);
            }}
            style="text-right"
            select={true}
            selectData={[
              { key: "مرد", value: 0 },
              { key: "زن", value: 1 },
            ]}
          />
        </div>

        {/* <DatePickerIran
          datePickerEvent={(e) => setBirthDate(e)}
          date={birthDate}
          zindex="z-[1000]"
        /> */}

        <div className="">
          <Input
            lable="شماره تماس"
            id="phoneNumber-id"
            name="phoneNumber"
            type={"number"}
            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={roleSelectCurrntData}
            inputEvent={(e) => {
              setRoleSelectCurrntData(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={roleSelectData}
            defaultValue={"انتخاب کنید"}
          />
        </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>

        {/* <div className="">
          <Input
            lable="پوزیشن مد نظر"
            id="positionId-id"
            name="positionId"
            type={"text"}
            inputEvent={(e) => {
              setPositionId(e.target.value);
            }}
            style="text-right"
            validatorData={validator.current.message(
              "positionId",
              positionId,
              "required"
            )}
            select={true}
            selectData={positionIdSelectData}
            defaultValue={"انتخاب کنید"}
          />
        </div>

        <div className="flex flex-wrap mt-3 rtl">
          <div className="flex bg-gray-300 p-1 rounded-full m-1 justify-start">
            <div>
              <p className="mb-0 px-3 text-sm mt-1">
                {positionsData?.find((b) => b.id == positionId)?.name}
              </p>
            </div>
          </div>
        </div> */}

        {goToEditUser ? (
          <Buttonbriz
            title="ویرایش کاربر"
            color="INFO"
            icon="CHECK"
            buttonEvent={() => handleCreateUser("UPDATE")}
            subButton={true}
            subButtonTitle="حذف کاربر"
            subButtonEvent={() => CTX.DeleteUser(idEditUser)}
          />
        ) : (
          <Buttonbriz
            title="ثبت کاربر"
            color="PRIMARY"
            icon="CHECK"
            buttonEvent={() => handleCreateUser()}
          />
        )}
      </div>
    </BottomSheet>
  );
};

export default BottomSheetCreateEmployees;
