"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 BottomManageShift = (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 [, 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 body = {
    phoneNumber,
    firstName,
    lastName,
    birthDateTimeStamp:
      birthDate &&
      moment
        .utc(
          [birthDate.year, birthDate.month, birthDate.day],
          "jYYYY-jMM-jDDTHH"
        )
        .unix(),
    gender: parseInt(gender),
    nationalId,
    roleIds: rolesChoose,
  };

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

  const clear = () => {
    setFirstName("");
    setLastName("");
    setPhoneNumber("");
    setNationalId("");
    setGender("");
    setBirthDate("");
    setRoleSelectCurrntData("");
    setRoleSelectData([]);
    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,
      }))
    );

    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);
    }
  }, [userData]);

  return (
    <BottomSheet
      onSpringStart={(e) => handleBottomSheetCreateEmployeesOpen(e)}
      open={CTX.state.BottomManageShiftOpen}
      onDismiss={() => CTX.setBottomManageShiftOpen(false)}
      blocking={true}
    >
      <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>
    </BottomSheet>
  );
};

export default BottomManageShift;
