import React, { useEffect, 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 { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import TreeSDK from "Utils/TreeSDK";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

let sdk = new MkdSDK();
let tdk = new TreeSDK();

const EditAdminStripePricePage = ({ activeId, setSidebar }) => {
  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 [id, setId] = useState(0);
  const [priceType, setPriceType] = useState("one_time");
  const [selectProduct, setSelectProduct] = useState([]);
  const [status, setStatus] = useState(0);
  const [loading, setLoading] = useState(false);

  const {
    register,
    handleSubmit,
    setError,
    setValue,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const watchType = watch("type");

  const selectType = [
    { key: "one_time", value: "ONE_TIME", display: "One Time" },
    { key: "recurring", value: "RECURRING", display: "Recurring" },
  ];

  const selectInterval = [
    { key: "day", value: "day", display: "Daily" },
    { key: "week", value: "week", display: "Weekly" },
    { key: "month", value: "month", display: "Monthly" },
    { key: "year", value: "year", display: "Yearly" },
  ];

  const selectUsageType = [
    { key: "licensed", value: "licensed", display: "Licensed" },
    { key: "metered", value: "metered", display: "Metered" },
  ];

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

    (async function () {
      try {
        const result = activeId
          ? await sdk.getStripePrice(activeId)
          : { error: true };
        if (!result.error) {
          const price = result.model;
          const priceObject = JSON.parse(price.object);
          setValue("product_id", price.product_id.toString());
          setValue("name", price.name);
          setValue("amount", price.amount);
          setValue("type", price.type);
          setPriceType(price.type);
          setValue("is_usage_metered", price.is_usage_metered === 1);
          setValue("usage_limit", price.usage_limit);
          setValue("trial_days", price.trial_days);
          setId(price.id);
          setStatus(price.status ? true : false);

          if (price.type === "recurring") {
            setValue("interval", priceObject.recurring.interval);
            setValue("interval_count", priceObject.recurring.interval_count);
            setValue("usage_type", priceObject.recurring.usage_type);
          }
        }

        // Fetch products for the dropdown
        const productsResult = await sdk.callRestAPI(
          {},
          "GET",
          "stripe/product"
        );
        if (!productsResult.error) {
          setSelectProduct(productsResult.list);
        }
      } catch (error) {
        console.log("Error", error);
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, [activeId]);

  const onSubmit = async (data) => {
    try {
      const result = await ("stripe_price",
      activeId,
      {
        amount: Number(data?.amount),
      });
      if (!result.error) {
        showToast(globalDispatch, "Updated", 4000);
        navigate("/admin/pricing");
      } else {
        if (result.validation) {
          const keys = Object.keys(result.validation);
          for (let i = 0; i < keys.length; i++) {
            const field = keys[i];
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
    } catch (error) {
      console.log("Error", error);
      showToast(globalDispatch, error.message, 4000);
      tokenExpireError(dispatch, error.message);
    }
  };

  return (
    <div className="relative z-50 flex h-full w-full items-center justify-center overflow-y-auto p-4">
      <div className="relative h-full w-full max-w-2xl md:h-auto">
        <div className="relative rounded-lg bg-boxdark">
          <div className="p-6">
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
              <div className="form-group">
                <label className="mb-2.5 block font-medium text-white">
                  Product
                </label>
                <input
                  type="text"
                  {...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"
                  readOnly
                />
                {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"
                  placeholder="Name"
                  {...register("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"
                  placeholder="Amount"
                  {...register("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")}
                  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.key} key={`type_${option.key}`}>
                      {option.display}
                    </option>
                  ))}
                </select>
                {errors.type && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.type?.message}
                  </p>
                )}
              </div>

              {watchType === "recurring" && (
                <div className="space-y-4 rounded-lg border border-stroke bg-boxdark-2 p-4">
                  <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}
                          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"
                      placeholder="Interval Count"
                      {...register("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}
                          key={`usage_type_${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"
                      placeholder="0"
                      {...register("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"
                      placeholder="1000"
                      {...register("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 className="form-group">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        {...register("is_usage_metered")}
                        className="h-5 w-5 rounded border-stroke bg-boxdark text-primary focus:ring-primary"
                      />
                      <span className="ml-2 text-sm font-medium text-white">
                        Is Usage Metered
                      </span>
                    </label>
                  </div>
                </div>
              )}
            </form>
          </div>

          {/* Modal Footer */}
          <div className="flex items-center justify-end gap-4 border-t border-stroke p-5">
            <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 EditAdminStripePricePage;
