
  import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import MkdSDK from "Utils/MkdSDK";
import { useNavigate } from "react-router-dom";
import { GlobalContext, showToast } from "Context/Global";
import { tokenExpireError, AuthContext } from "Context/Auth";

const AddAdminStripePricePage = ({ setSidebar }) => {
  const [priceType, setPriceType] = useState("one_time");
  const [selectProduct, setSelectProduct] = useState([]);
  const [isUpdatingPrice, setIsUpdatingPrice] = useState(false);

  const schema = yup
    .object({
      product_id: yup.string().required(),
      name: yup.string().required(),
      amount: yup.string().required(),
      type: yup.string().required(),
      interval: yup.string().when("type", {
        is: "recurring",
        then: (schema) => schema.required(),
        otherwise: (schema) => schema.notRequired(),
      }),
      interval_count: yup.string(),
      usage_type: yup.string().when("type", {
        is: "recurring",
        then: (schema) => schema.required(),
        otherwise: (schema) => schema.notRequired(),
      }),
      usage_limit: yup.string(),
      trial_days: yup.string(),
    })
    .required();

  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    trigger,
    resetField,
    getValues,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const selectType = [
    { key: 0, value: "", display: "Nothing Selected" },
    { key: 1, value: "one_time", display: "One Time" },
    { key: 2, value: "recurring", display: "Recurring" },
  ];

  const selectUsageType = [
    { key: 0, value: "", display: "Nothing Selected" },
    { key: 1, value: "licenced", display: "Upfront" },
    { key: 2, value: "metered", display: "Metered" },
  ];

  const selectInterval = [
    { key: 0, value: "", display: "Nothing Selected" },
    { key: 1, value: "day", display: "Day" },
    { key: 2, value: "week", display: "Week" },
    { key: 3, value: "month", display: "Month" },
    { key: 4, value: "year", display: "Year" },
    { key: 5, value: "lifetime", display: "Lifetime" },
  ];

  const onSubmit = async (data) => {
    let sdk = new MkdSDK();
    console.log(data);
    setIsUpdatingPrice(true);
    try {
      const result = await sdk.addStripePrice(data);
      if (!result.error) {
        showToast(globalDispatch, "Price Added");
        navigate("/admin/prices");
      } else {
        if (result.validation) {
          const keys = Object.keys(result.validation);
          for (let i = 0; i < keys.length; i++) {
            const field = keys[i];
            console.log(field);
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
    } catch (error) {
      console.log("Error", error);

      showToast(globalDispatch, error.message);
      tokenExpireError(dispatch, error.message);
    }
    setIsUpdatingPrice(false);
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "prices",
      },
    });
    (async () => {
      let sdk = new MkdSDK();
      const { list, error } = await sdk.getStripeProducts({ limit: "all" });
      if (error) {
        showToast(
          dispatch,
          "Something went wrong while fetching products list"
        );
        return;
      }
      setSelectProduct(list);
    })();
  }, []);
  return (
    <div className=" mx-auto  rounded">
      <div
        className={`flex items-center justify-between gap-4 border-b border-b-[#E0E0E0] p-3`}
      >
        <div className="flex items-center gap-3">
          (/* <svg
            onClick={() => setSidebar(false)}
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
          >
            <path
              d="M14.3322 5.83203L19.8751 11.3749C20.2656 11.7654 20.2656 12.3986 19.8751 12.7891L14.3322 18.332M19.3322 12.082H3.83218"
              stroke="#A8A8A8"
              stroke-width="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg> */)
          <span className="text-lg font-semibold">Add Price</span>
        </div>
        <div className="flex items-center gap-4">
          <button
            className="flex items-center rounded-md border border-[#C6C6C6] px-3 py-2 shadow-sm hover:bg-[#f4f4f4]"
            onClick={() => setSidebar(false)}
          >
            Cancel
          </button>
          <button
            className="flex items-center rounded-md bg-[#4F46E5] px-3 py-2 text-white shadow-sm"
            onClick={async () => {
              await handleSubmit(onSubmit)();
              setSidebar(false);
            }}
            disabled={isUpdatingPrice}
          >
            {isUpdatingPrice ? "Saving..." : "Save"}
          </button>
        </div>
      </div>
      <form
        className=" w-full p-4 text-left"
        onSubmit={handleSubmit(onSubmit)}
      >
        <div className="mb-4 ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="product_id"
          >
            Product
          </label>
          <select
            className="focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
            {...register("product_id")}
          >
            <option value="" key={`prod_default`}>
              Nothing selected
            </option>
            {selectProduct.map((option, index) => (
              <option value={option.id} key={`prod_${option.id}`}>
                {option.name}
              </option>
            ))}
          </select>
          <p className="text-xs italic text-red-500">
            {errors.product_id?.message}
          </p>
        </div>

        <div className="mb-4 ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="name"
          >
            Name
          </label>
          <input
            type="text"
            placeholder="Name"
            {...register("name")}
            className={`"shadow focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 focus:outline-none ${errors.name?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">{errors.name?.message}</p>
        </div>

        <div className="mb-5">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="amount"
          >
            Amount
          </label>
          <input
            type="number"
            min={0.1}
            step="any"
            placeholder="Amount"
            {...register("amount")}
            className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.amount?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">
            {errors.amount?.message}
          </p>
        </div>

        <div className="mb-5">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="type"
          >
            Type
          </label>
          <select
            className="focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
            {...register("type")}
            onChange={(e) => {
              const currentTypeSelected = e.target.value;
              setPriceType(currentTypeSelected);
              setValue("type", currentTypeSelected);
              trigger("type");
            }}
          >
            {selectType.map((option) => (
              <option
                value={option.value.toLowerCase()}
                key={`interval_${option.key}`}
              >
                {option.display}
              </option>
            ))}
          </select>
          <p className="text-xs italic text-red-500">{errors.type?.message}</p>
        </div>
        {priceType === "recurring" ? (
          <div className="ml-6">
            <div className="mb-5">
              <label
                className="mb-2 block text-sm font-bold text-gray-700"
                htmlFor="interval"
              >
                Interval
              </label>
              <select
                className="focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
                {...register("interval")}
                placeholder="Select"
              >
                {selectInterval.map((option) => (
                  <option
                    value={option.value.toLowerCase()}
                    key={`interval_${option.key}`}
                  >
                    {option.display}
                  </option>
                ))}
              </select>
              <p className="text-xs italic text-red-500">
                {errors.interval?.message}
              </p>
            </div>
            <div className="mb-5">
              <label
                className="mb-2 block text-sm font-bold text-gray-700"
                htmlFor="interval_count"
              >
                Interval Count
              </label>
              <input
                type="number"
                step="1"
                placeholder="Interval Count"
                {...register("interval_count")}
                {...setValue("interval_count", 1)}
                className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.interval_count?.message ? "border-red-500" : ""
                  }`}
              />
              <p className="text-xs italic text-red-500">
                {errors.interval_count?.message}
              </p>
            </div>

            <div className="mb-5">
              <label
                className="mb-2 block text-sm font-bold text-gray-700"
                htmlFor="usage_type"
              >
                Usage Type
              </label>
              <select
                className="focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
                {...register("usage_type")}
                placeholder="Select"
              >
                {selectUsageType.map((option) => (
                  <option
                    value={option.value.toLowerCase()}
                    key={`interval_${option.key}`}
                  >
                    {option.display}
                  </option>
                ))}
              </select>
              <p className="text-xs italic text-red-500">
                {errors.usage_type?.message}
              </p>
            </div>
            <div className="mb-5">
              <label
                className="mb-2 block text-sm font-bold text-gray-700"
                htmlFor="trial_days"
              >
                Trial Days
              </label>
              <input
                type="number"
                step="1"
                placeholder="0"
                {...register("trial_days")}
                className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.trial_days?.message ? "border-red-500" : ""
                  }`}
              />
              <p className="text-xs italic text-red-500">
                {errors.trial_days?.message}
              </p>
            </div>
            <div className="mb-5">
              <label
                className="mb-2 block text-sm font-bold text-gray-700"
                htmlFor="trial_days"
              >
                Usage Limit
              </label>
              <input
                type="number"
                step="1"
                placeholder="1000"
                {...register("usage_limit")}
                className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.usage_limit?.message ? "border-red-500" : ""
                  }`}
              />
              <p className="text-xs italic text-red-500">
                {errors.usage_limit?.message}
              </p>
            </div>
          </div>
        ) : (
          ""
        )}

        {/* <button
          type="submit"
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
        >
          Submit
        </button> */}
      </form>
    </div>
  );
};

export default AddAdminStripePricePage;

  