"use client";
import AppHeader from "@comp/AppHeader/page";
import { useRouter } from "next/navigation";
import React, { useContext, useEffect, useState } from "react";
import SimpleReactValidator from "simple-react-validator";
import Input from "plugins/Input/page";
import { useRef } from "react";
import Buttonbriz from "plugins/Buttonbriz/page";
import CoffeeBrewCard from "@comp/CoffeeBrew/CoffeeBrewCard/page";
import AppContext from "@ctx/AppContext";
import Chapar from "plugins/Chapar";
import { toast } from "react-toastify";
import CoffeeBrewChart from "plugins/Charts/CoffeeBrewChart";

const page = () => {
  const router = useRouter();
  const CTX = useContext(AppContext);
  const coffeeBrewData = CTX.state.coffeeBrewData;

  const [ratio, setRatio] = useState(null);
  const [extractionTime, setExtractionTime] = useState(null);
  const [finalYield, setFinalYield] = useState(null);

  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 clear = () => {
    setRatio(""), setExtractionTime(""), setFinalYield("");
  };

  const body = {
    ratio,
    extractionTime,
    finalYield,
  };

  const CreateBrew = async () => {
    CTX.setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/brew/CoffeeBrew`,
        JSON.stringify(body)
      );
      toast.success(`ادجاست ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      clear();
      CTX.setLoading(false);
      CTX.GetCoffeeBrewData();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };

  useEffect(() => {
    CTX.GetCoffeeBrewData();
  }, []);

  return (
    <>
      {" "}
      <div className="pb-20">
        <AppHeader
          title="ادجاست قهوه"
          sub="مکانیزم ادجاست قهوه"
          // icon1={true}
          // iconName1="PLUS"
          // iconHref1="#"
          // iconEvent1={() => {
          //   CTX.setBottomSheetCreateShiftsOpen(true);
          // }}
          icon2={true}
          iconName2="ARROW"
          iconHref2="#"
          iconEvent2={() => {
            return router.back();
          }}
        />

        <div className="bg-white overflow-hidden p-5 rtl">
          <div className="">
            <Input
              lable=" BCG | گرماژ قهوه "
              id="ratio-id"
              theme={1}
              name="ratio"
              type={"number"}
              value={ratio}
              inputEvent={(e) => {
                setRatio(e.target.value);
                validator.current.showMessageFor("ratio");
              }}
              style="text-right"
              validator={true}
              validatorData={validator.current.message(
                "ratio",
                ratio,
                "required"
              )}
              mt={"5"}
            />
          </div>
          <div className="">
            <Input
              lable=" OEG | زمان عصاره گیری"
              id="extractionTime-id"
              theme={1}
              name="extractionTime"
              type={"number"}
              value={extractionTime}
              inputEvent={(e) => {
                setExtractionTime(e.target.value);
                validator.current.showMessageFor("extractionTime");
              }}
              style="text-right"
              validator={true}
              validatorData={validator.current.message(
                "extractionTime",
                extractionTime,
                "required"
              )}
              mt={"5"}
            />
          </div>

          <div className="">
            <Input
              lable="ET | گرماژ عصاره خروجی"
              id="finalYield-id"
              theme={1}
              name="finalYield"
              type={"number"}
              value={finalYield}
              inputEvent={(e) => {
                setFinalYield(e.target.value);
                validator.current.showMessageFor("finalYield");
              }}
              style="text-right"
              validator={true}
              validatorData={validator.current.message(
                "finalYield",
                finalYield,
                "required"
              )}
              mt={"5"}
            />
          </div>

          <div>
            {" "}
            <Buttonbriz
              title="ثبت"
              color="PRIMARY"
              icon="CHECK"
              buttonEvent={() => CreateBrew()}
            />
          </div>

          <h3 className="text-right px-3 pb-1 font-medium mt-7 text-sm">
            تاریخچه ادجاست ها
          </h3>

          <CoffeeBrewChart data={coffeeBrewData?.pastRecipes} />

          {coffeeBrewData?.pastRecipes?.map((e) => (
            <CoffeeBrewCard data={e} />
          ))}
        </div>
      </div>
    </>
  );
};

export default page;
