import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useNavigate } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { LazyLoad } from "Components/LazyLoad";
import { InteractiveButton } from "Components/InteractiveButton";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import MkdSDK from "Utils/MkdSDK";

const AdminStripePricesAddPage = ({ onSuccess, setSidebar }) => {
  let sdk = new MkdSDK();
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [loading, setLoading] = useState(false);

  const [priceType, setPriceType] = useState("one_time");
  const [selectProduct, setSelectProduct] = useState([]);

  const navigate = useNavigate();

  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 {
    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) => {
    console.log(data);
    try {
      setLoading(true);
      const result = await sdk.addStripePrice(data);
      if (!result.error) {
        showToast(globalDispatch, "Price Added", 5000, "success");
        if (onSuccess) {
          onSuccess();
        }
      } 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, 5000, "error");
      tokenExpireError(dispatch, error.message);
    } finally {
      setLoading(globalDispatch, false, "addStripePrice");
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "pricing",
      },
    });

    (async () => {
      const { list, error } = await sdk.getStripeProducts({ limit: "all" });
      if (error) {
        showToast(
          globalDispatch,
          "Something went wrong while fetching products list",
          5000,
          "error"
        );
        return;
      }
      setSelectProduct(list);
    })();
  }, []);

  return (
    <div className="flex overflow-y-auto relative z-50 justify-center items-center p-4 w-full h-full">
      <div className="relative w-full max-w-2xl h-full md:h-auto">
        <div className="relative rounded-lg bg-boxdark">
          {/* Modal Header */}

          {/* Modal Body */}
          <div className="">
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
              <div className="form-group">
                <label className="mb-2.5 block font-medium text-white">
                  Product
                </label>
                <select
                  {...register("product_id")}
                  className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                >
                  <option value="">Select a product</option>
                  {selectProduct.map((option) => (
                    <option value={option.id} key={`prod_${option.id}`}>
                      {option.name}
                    </option>
                  ))}
                </select>
                {errors.product_id && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.product_id.message}
                  </p>
                )}
              </div>

              <div className="form-group">
                <label className="mb-2.5 block font-medium text-white">
                  Name
                </label>
                <input
                  type="text"
                  {...register("name")}
                  placeholder="Enter price name"
                  className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                />
                {errors.name && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.name.message}
                  </p>
                )}
              </div>

              <div className="form-group">
                <label className="mb-2.5 block font-medium text-white">
                  Amount
                </label>
                <input
                  type="number"
                  min={0.1}
                  step="any"
                  {...register("amount")}
                  placeholder="Enter amount"
                  className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                />
                {errors.amount && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.amount.message}
                  </p>
                )}
              </div>

              <div className="form-group">
                <label className="mb-2.5 block font-medium text-white">
                  Type
                </label>
                <select
                  {...register("type")}
                  onChange={(e) => {
                    const currentTypeSelected = e.target.value;
                    setPriceType(currentTypeSelected);
                    setValue("type", currentTypeSelected);
                    trigger("type");
                  }}
                  className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                >
                  {selectType.map((option) => (
                    <option
                      value={option.value.toLowerCase()}
                      key={`type_${option.key}`}
                    >
                      {option.display}
                    </option>
                  ))}
                </select>
                {errors.type && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.type.message}
                  </p>
                )}
              </div>

              {priceType === "recurring" && (
                <div className="p-4 space-y-4 rounded-lg border border-stroke bg-boxdark-2">
                  <h4 className="mb-4 font-medium text-white">
                    Recurring Settings
                  </h4>

                  <div className="form-group">
                    <label className="mb-2.5 block font-medium text-white">
                      Interval
                    </label>
                    <select
                      {...register("interval")}
                      className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      {selectInterval.map((option) => (
                        <option
                          value={option.value.toLowerCase()}
                          key={`interval_${option.key}`}
                        >
                          {option.display}
                        </option>
                      ))}
                    </select>
                    {errors.interval && (
                      <p className="mt-1 text-xs text-danger">
                        {errors.interval.message}
                      </p>
                    )}
                  </div>

                  <div className="form-group">
                    <label className="mb-2.5 block font-medium text-white">
                      Interval Count
                    </label>
                    <input
                      type="number"
                      step="1"
                      {...register("interval_count")}
                      placeholder="Enter interval count"
                      className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    />
                    {errors.interval_count && (
                      <p className="mt-1 text-xs text-danger">
                        {errors.interval_count.message}
                      </p>
                    )}
                  </div>

                  <div className="form-group">
                    <label className="mb-2.5 block font-medium text-white">
                      Usage Type
                    </label>
                    <select
                      {...register("usage_type")}
                      className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      {selectUsageType.map((option) => (
                        <option
                          value={option.value.toLowerCase()}
                          key={`usage_${option.key}`}
                        >
                          {option.display}
                        </option>
                      ))}
                    </select>
                    {errors.usage_type && (
                      <p className="mt-1 text-xs text-danger">
                        {errors.usage_type.message}
                      </p>
                    )}
                  </div>

                  <div className="form-group">
                    <label className="mb-2.5 block font-medium text-white">
                      Trial Days
                    </label>
                    <input
                      type="number"
                      step="1"
                      {...register("trial_days")}
                      placeholder="Enter trial days"
                      className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    />
                    {errors.trial_days && (
                      <p className="mt-1 text-xs text-danger">
                        {errors.trial_days.message}
                      </p>
                    )}
                  </div>

                  <div className="form-group">
                    <label className="mb-2.5 block font-medium text-white">
                      Usage Limit
                    </label>
                    <input
                      type="number"
                      step="1"
                      {...register("usage_limit")}
                      placeholder="Enter usage limit"
                      className="w-full rounded-lg border border-stroke bg-boxdark px-4 py-2.5 text-white focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    />
                    {errors.usage_limit && (
                      <p className="mt-1 text-xs text-danger">
                        {errors.usage_limit.message}
                      </p>
                    )}
                  </div>
                </div>
              )}
            </form>
          </div>

          {/* Modal Footer */}
          <div className="flex gap-4 justify-end items-center p-5 border-t border-stroke">
            <button
              onClick={() => setSidebar(false)}
              className="rounded-lg border border-stroke bg-boxdark px-6 py-2.5 text-white hover:bg-opacity-90"
            >
              Cancel
            </button>
            <button
              onClick={handleSubmit(onSubmit)}
              disabled={loading}
              className="rounded-lg bg-primary px-6 py-2.5 text-white hover:bg-opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {loading ? "Saving..." : "Save Price"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AdminStripePricesAddPage;
