"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";

const BottomSheetCreatePosition = (props) => {
  const CTX = useContext(AppContext);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [sectionId, setSectionId] = useState("");
  const [sectionIdSelectData, setSectionIdSelectData] = useState("");
  const [sectionIdSelectCurrntData, setSectionIdSelectCurrntData] =
    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 goToEditPosition = CTX.state.goToEditPosition;
  const idEditPosition = CTX.state.idEditPosition;
  const positionData = CTX.state.positionData;
  const sectionIdChoose = CTX.state.sectionIdChoose;
  const sectionsData = CTX.state.sectionsData;

  const body = {
    description,
    title,
    sectionId,
  };

  const bodyUpdate = {
    description,
    title,
    sectionId,
    id: idEditPosition,
  };

  const clear = () => {
    setTitle("");
    setDescription("");
    setSectionId("");
    setSectionIdSelectCurrntData("");
  };

  const handleCreatePosition = (update) => {
    if (validator.current.allValid()) {
      if (update == "UPDATE") {
        CTX.UpdatePosition(bodyUpdate);
      } else {
        CTX.CreatePosition(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 handleBottomSheetCreatePositionOpen = (e) => {
    setSectionIdSelectData(
      sectionsData?.map((item) => ({
        key: item.name,
        value: item.id,
      }))
    );
    if (e.type == "OPEN") {
      CTX.GetSections();
      if (goToEditPosition) {
        CTX.GetPosition(idEditPosition);
      }
    } else if (e.type == "CLOSE") {
      clear();
      CTX.setGoToEditPosition(false);
      CTX.setIdEditPosition(null);
      CTX.setPositionData([]);
    }
  };

  const deleteSection = (id) => {
    CTX.setSectionIdChoose(sectionIdChoose.filter((el) => el !== id));
  };

  useEffect(() => {
    if (goToEditPosition) {
      setTitle(positionData.name);
      setDescription(positionData.description);
      setSectionId(positionData.sectionId);
    }
  }, [positionData]);

  return (
    <BottomSheet
      onSpringStart={(e) => handleBottomSheetCreatePositionOpen(e)}
      open={CTX.state.BottomSheetCreatePositionOpen}
      onDismiss={() => CTX.setBottomSheetCreatePositionOpen(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="title-id"
            name="title"
            type={"text"}
            value={title}
            inputEvent={(e) => {
              setTitle(e.target.value);
              validator.current.showMessageFor("title");
            }}
            style="text-right"
            validator={true}
            validatorData={validator.current.message(
              "title",
              title,
              "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"
            validator={true}
            validatorData={validator.current.message(
              "description",
              description,
              "required"
            )}
          />
        </div>

        <div className="">
          <Input
            lable="سکشن مد نظر"
            id="sectionId-id"
            name="sectionId"
            type={"text"}
            value={sectionIdSelectCurrntData}
            inputEvent={(e) => {
              setSectionId(e.target.value);
              // setSectionId(e.target.value);
              // if (!!sectionIdChoose.find((b) => b == e.target.value)) {
              //   toast.error("سکشن تکراری است", {
              //     position: "bottom-right",
              //     closeOnClick: true,
              //   });
              // } else {
              //   CTX.setSectionIdChoose((current) => [
              //     ...current,
              //     e.target.value,
              //   ]);
              // }
            }}
            style="text-right"
            validatorData={validator.current.message(
              "sectionId",
              sectionId,
              "required"
            )}
            select={true}
            selectData={sectionIdSelectData}
            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
              className="w-[30px] h-[30px] rounded-full bg-gray-400 "
              onClick={() => deleteSection(e)}
            ></div> */}

            <div>
              <p className="mb-0 px-3 text-sm mt-1">
                {sectionsData?.find((b) => b.id == sectionId)?.name}
              </p>
            </div>
          </div>
        </div>

        {goToEditPosition ? (
          <Buttonbriz
            title="ویرایش پوزیشن"
            color="INFO"
            icon="CHECK"
            buttonEvent={() => handleCreatePosition("UPDATE")}
            subButton={true}
            subButtonTitle="حذف پوزیشن"
            subButtonEvent={() => CTX.DeletePosition(idEditPosition)}
          />
        ) : (
          <Buttonbriz
            title="ثبت پوزیشن"
            color="PRIMARY"
            icon="CHECK"
            buttonEvent={() => handleCreatePosition()}
          />
        )}
      </div>
    </BottomSheet>
  );
};

export default BottomSheetCreatePosition;
