"use client";
import Navbar from "@comp/Navbar/page";
import React, { useContext, useEffect, useRef, useState } from "react";
import SideBarProfile from "../component/SideBarProfile/page";
import SimpleReactValidator from "simple-react-validator";
import { toast } from "react-toastify";
import PersianNumber from "plugins/PersianNumber";
import AppContext from "@ctx/AppContext";
import moment from "jalali-moment";
import Chapar from "plugins/Chapar";

const Page = () => {
  const CTX = useContext(AppContext);
  const cooperationSystemProfileContractData =
    CTX.state.cooperationSystemProfileContractData;

  const cooperationSystemProfileData = CTX.state.cooperationSystemProfileData;
  const profile = CTX.state.profile;
  const [stepsaleCooperationSystem, setStepsaleCooperationSystem] = useState(0);
  const [rulesAccept, setRulesAccept] = useState(false);
  const [nationalCode, setNationalCode] = useState("");
  const [fatherName, setFatherName] = useState("");
  const [shabaNumber, setShabaNumber] = useState("");
  const [year, setYear] = useState("");
  const [month, setMonth] = useState("");
  const [day, setDay] = useState("");
  const [birthDate, setBirthDate] = useState("");

  const [, forceUpdate] = useState();
  const [submited, setSubmited] = useState(false);

  const validator = useRef(
    new SimpleReactValidator({
      messages: {
        required: "پر کردن این فیلد الزامی میباشد",
      },
      element: (message) => (
        <>
          <div className="text-right px-1 text-sm">
            <small className="text-red-600  t-ig-small ">{message}</small>
          </div>
        </>
      ),
    })
  );

  // Generate options for days and months
  const daysOptions = Array.from({ length: 31 }, (_, i) => i + 1);
  const monthsOptions = Array.from({ length: 12 }, (_, i) => i + 1);
  // Generate options for years between 1340 and 1388
  const yearsOptions = Array.from({ length: 49 }, (_, i) => 1388 - i);

  const body = {
    fatherName,
    nationalId: nationalCode,
    shaba: shabaNumber,
    birthDate,
  };

  const handleBirthDate = (year, month, day) => {
    setDay(day);
    setMonth(month);
    setYear(year);
    const persianDate = `${year}/${month}/${day}`;
    // Convert Persian date to timestamp
    const timestamp = moment(persianDate, "jYYYY/jM/jD").unix();
    setBirthDate(timestamp);
  };

  const sendInfoUserCooperationSystem = async () => {
    if (validator.current.allValid()) {
      try {
        const data = await Chapar.post(
          `${process.env.NEXT_PUBLIC_API_URL}/marketer/signup`,
          JSON.stringify(body),
          {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          }
        );

        CTX.setCooperationSystemProfileData(data);
        setStepsaleCooperationSystem(2);
      } catch ({ error, status }) {
        toast.error("مشکلی در ارسال اطلاعات رخ داده است", {
          position: "bottom-right",
          autoClose: 2000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      }
    } else {
      toast.error("پرکردن همه ی فیلد ها واجب است", {
        position: "bottom-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
      validator.current.showMessages();
      forceUpdate(1);
    }
  };

  useEffect(() => {
    if (profile.isMarketer) {
      CTX.fetchCooperationSystemProfile();
      setStepsaleCooperationSystem(2);
    } else {
      CTX.fetchCooperationSystemProfileContract();
      setStepsaleCooperationSystem(0);
    }
  }, [profile]);

  return (
    <>
      <Navbar theme={1} />
      <div className="grid xs:grid-cols-1 lg:grid-cols-4 xl:grid-cols-5  rtl gap-6 xs:px-[20px] lg:px-[100px] xl:[300px]">
        <SideBarProfile />

        <div className="lg:col-span-3 xl:col-span-4 mb-20 ">
          <div className="bg-gray-100 p-4 mt-5 rounded-lg overflow-hidden">
            <div className="flex mb-10">
              <div
                className={`xs:pr-2 lg:pr-4 ${
                  stepsaleCooperationSystem == 0 ? "" : " opacity-40"
                }`}
              >
                <p
                  className={`mb-0 xs:text-[12px] lg:text-base  ${
                    stepsaleCooperationSystem == 0 ? "font-bold" : "font-medium"
                  }`}
                >
                  قوانین همکاری
                </p>
              </div>
              <div
                className={`xs:pr-2 lg:pr-4 ${
                  stepsaleCooperationSystem == 1 ? "" : " opacity-40"
                }`}
              >
                <p
                  className={`mb-0 xs:text-[12px] lg:text-base  ${
                    stepsaleCooperationSystem == 1 ? "font-bold" : "font-medium"
                  }`}
                >
                  اطلاعات تکمیلی
                </p>
              </div>
              <div
                className={`xs:pr-2 lg:pr-4 ${
                  stepsaleCooperationSystem == 2 ? "" : " opacity-40"
                }`}
              >
                <p
                  className={`mb-0 xs:text-[12px] lg:text-base  ${
                    stepsaleCooperationSystem == 2 ? "font-bold" : "font-medium"
                  }`}
                >
                  داشبورد
                </p>
              </div>
            </div>

            {stepsaleCooperationSystem == 0 ? (
              <div className="pr-5">
                <div
                  dangerouslySetInnerHTML={{
                    __html: cooperationSystemProfileContractData,
                  }}
                />

                <div className="flex mt-10 cursor-pointer">
                  <input
                    id="checkBox"
                    type="checkbox"
                    className="scale-150"
                    onChange={(e) => {
                      setRulesAccept(e.target.checked);
                    }}
                  />
                  <label
                    htmlFor="checkBox"
                    className="mb-0 text-sm font-bold mr-2"
                  >
                    {" "}
                    قوانین را مطالعه کرده و آن را میپذیرم{" "}
                  </label>
                </div>

                {!rulesAccept ? (
                  <div className="mt-10">
                    <button className="btn btn-primary rounded-full text-sm p-3 !px-5 opacity-45">
                      مرحله بعد
                    </button>
                  </div>
                ) : (
                  <div
                    className="mt-10"
                    onClick={() => setStepsaleCooperationSystem(1)}
                  >
                    <button className="btn btn-primary rounded-full text-sm p-3 !px-5">
                      مرحله بعد
                    </button>
                  </div>
                )}
              </div>
            ) : stepsaleCooperationSystem == 1 ? (
              <div className="pr-2">
                <div className="grid xs:grid-cols-1 lg:grid-cols-2 gap-8 ">
                  <div className="text-right my-2">
                    <div className=" rtl pb-2 pr-3">
                      <label className=" px-2 text-sm ml-0 text-gray-500  ">
                        کد ملی
                        <small className="text-red-900">*</small>
                      </label>
                    </div>
                    <input
                      type="text"
                      className={`form-control`}
                      name="nationalCode"
                      value={nationalCode}
                      maxLength={11}
                      onChange={(e) => {
                        setNationalCode(e.target.value);
                        validator.current.showMessageFor("nationalCode");
                      }}
                    />
                    {!submited ? (
                      <>
                        {validator.current.message(
                          "nationalCode",
                          nationalCode,
                          "required"
                        )}
                      </>
                    ) : (
                      ""
                    )}
                  </div>

                  <div className="text-right my-2">
                    <div className=" rtl pb-2 pr-3">
                      <label className=" px-2 text-sm ml-0 text-gray-500  ">
                        نام پدر <small className="text-red-900">*</small>
                      </label>
                    </div>
                    <input
                      type="text"
                      className={`form-control`}
                      name="fatherName"
                      value={fatherName}
                      maxLength={11}
                      onChange={(e) => {
                        setFatherName(e.target.value);
                        validator.current.showMessageFor("fatherName");
                      }}
                    />
                    {!submited ? (
                      <>
                        {validator.current.message(
                          "fatherName",
                          fatherName,
                          "required"
                        )}
                      </>
                    ) : (
                      ""
                    )}
                  </div>

                  <div className="text-right my-2">
                    <div className=" rtl pb-2 pr-3">
                      <label className=" px-2 text-sm ml-0 text-gray-500  ">
                        شماره شبا<small className="text-red-900">*</small>
                      </label>
                    </div>
                    <div className="flex">
                      <input
                        type="text"
                        className={`form-control !text-left`}
                        name="shabaNumber"
                        value={shabaNumber}
                        onChange={(e) => {
                          setShabaNumber(e.target.value);
                          validator.current.showMessageFor("shabaNumber");
                        }}
                      />
                      <div className="w-[40px] mr-2">
                        <p className="ltr text-gray-700 font-bold mt-4">
                          IR -{" "}
                        </p>
                      </div>
                    </div>
                    {!submited ? (
                      <>
                        {validator.current.message(
                          "shabaNumber",
                          shabaNumber,
                          "required"
                        )}
                      </>
                    ) : (
                      ""
                    )}
                  </div>

                  <div className="text-right my-2">
                    <div className=" rtl pb-2 pr-3">
                      <label className=" px-2 text-sm ml-0 text-gray-500  ">
                        تاریخ تولد<small className="text-red-900">*</small>
                      </label>
                    </div>
                    <div className="flex ltr">
                      <select
                        type="number"
                        className={`form-control !text-center mx-1`}
                        name="year"
                        value={year}
                        onChange={(e) => {
                          handleBirthDate(e.target.value, month, day);
                          validator.current.showMessageFor("year");
                        }}
                        placeholder="سال"
                        maxLength={4}
                      >
                        {yearsOptions.map((y) => (
                          <option key={y} value={y}>
                            {y}
                          </option>
                        ))}
                      </select>

                      <select
                        type="number"
                        className={`form-control !text-center mx-1`}
                        name="month"
                        value={month}
                        onChange={(e) => {
                          handleBirthDate(year, e.target.value, day);
                          validator.current.showMessageFor("month");
                        }}
                        placeholder="ماه"
                        maxLength={2}
                      >
                        {monthsOptions.map((m) => (
                          <option key={m} value={m}>
                            {m}
                          </option>
                        ))}
                      </select>

                      <select
                        type="number"
                        className={`form-control !text-center mx-1`}
                        name="day"
                        value={day}
                        onChange={(e) => {
                          handleBirthDate(year, month, e.target.value);
                          validator.current.showMessageFor("day");
                        }}
                        placeholder="روز"
                        maxLength={4}
                      >
                        {daysOptions.map((d) => (
                          <option key={d} value={d}>
                            {d}
                          </option>
                        ))}
                      </select>
                    </div>
                    {!submited ? (
                      <div className="flex">
                        <>{validator.current.message("day", day, "required")}</>
                        <>
                          {validator.current.message("year", year, "required")}
                        </>
                        <>
                          {validator.current.message(
                            "month",
                            month,
                            "required"
                          )}
                        </>
                      </div>
                    ) : (
                      ""
                    )}
                  </div>
                </div>

                <div
                  className="mt-10"
                  onClick={() => sendInfoUserCooperationSystem()}
                >
                  <button className="btn btn-primary rounded-full text-sm p-3 !px-5">
                    مرحله بعد
                  </button>
                </div>
              </div>
            ) : stepsaleCooperationSystem == 2 ? (
              <div className="grid xs:grid-cols-1 lg:grid-cols-4 gap-8">
                <div className="xs:col-span-1 lg:col-span-2 ">
                  <div className="bg-white rounded-2xl p-5 ">
                    <p className="  text-sm mb-2 text-center font-medium text-primary-600">
                      کد معرف شما{" "}
                    </p>

                    <div className="bg-gray-200 p-5 rounded-2xl">
                      <p className="mb-0 font-bold text-center">
                        {cooperationSystemProfileData?.discountCode}
                      </p>
                    </div>
                  </div>
                </div>

                <div>
                  <div className="bg-primary-500 text-center rounded-2xl p-10">
                    <PersianNumber
                      number={cooperationSystemProfileData?.orderCount}
                      style={"text-white !text-[30px]"}
                    />
                    <p className="mb-0 text-sm text-center text-white mt-1">
                      فروش شما
                    </p>
                  </div>
                </div>

                <div>
                  <div className="bg-green-700 text-center rounded-2xl p-10">
                    <div className="flex justify-center">
                      <PersianNumber
                        number={cooperationSystemProfileData?.balance}
                        style={"text-white !text-[30px]"}
                      />

                      <small className="text-white mr-1 opacity-70">
                        تومان
                      </small>
                    </div>
                    <p className="mb-0 text-sm text-center text-white mt-1">
                      سود شما از خرید{" "}
                    </p>
                  </div>
                </div>
              </div>
            ) : (
              ""
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default Page;
