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 "Src/authContext";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

const AddAdminStripePricePage = ({ setSidebar, onSuccess = null }) => {
  const [priceType, setPriceType] = useState("one_time");
  const [selectProduct, setSelectProduct] = useState([]);
  const [isLoading, setIsLoading] = 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,
    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();
    setIsLoading(true);
    try {
      const result = await sdk.addStripePrice(data);
      if (!result.error) {
        showToast(globalDispatch, "Price Added");
        if (onSuccess) {
          onSuccess();
        } else {
          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];
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
    } catch (error) {
      console.log("Error", error);
      showToast(globalDispatch, error.message);
      tokenExpireError(dispatch, error.message);
    }
    setIsLoading(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="fixed inset-0 z-50 flex items-center justify-center">
      <div
        className="fixed inset-0 bg-black/50 backdrop-blur-sm"
        onClick={() => setSidebar(false)}
      />
      <div className="shadow-default w-full max-w-xl transform rounded border border-strokedark bg-boxdark transition-all">
        <form onSubmit={handleSubmit(onSubmit)}>
          {/* Modal Header */}
          <div className="flex items-center justify-between border-b border-stroke px-6 py-4">
            <div className="flex items-center gap-3">
              <FontAwesomeIcon
                icon="fa-solid fa-dollar-sign"
                className="text-xl text-primary"
              />
              <h3 className="text-xl font-medium text-white">Add Price</h3>
            </div>
            <button
              onClick={() => setSidebar(false)}
              className="hover:text-primary"
              type="button"
            >
              <FontAwesomeIcon icon="fa-solid fa-xmark" className="text-2xl" />
            </button>
          </div>

          {/* Form Content */}
          <div className="p-6">
            <div className="space-y-4">
              {/* Product Selection */}
              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Product
                </label>
                <select
                  {...register("product_id")}
                  className="px-4.5 w-full rounded border border-stroke bg-boxdark py-3 text-white focus:border-primary focus:outline-none"
                >
                  <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>

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

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

              {/* Type Selection */}
              <div>
                <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="px-4.5 w-full rounded border border-stroke bg-boxdark py-3 text-white focus:border-primary focus:outline-none"
                >
                  {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>

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

                  {/* Interval Selection */}
                  <div>
                    <label className="mb-2.5 block font-medium text-white">
                      Interval
                    </label>
                    <select
                      {...register("interval")}
                      className="px-4.5 w-full rounded border border-stroke bg-boxdark py-3 text-white focus:border-primary focus:outline-none"
                    >
                      {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>

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

                  {/* Usage Type */}
                  <div>
                    <label className="mb-2.5 block font-medium text-white">
                      Usage Type
                    </label>
                    <select
                      {...register("usage_type")}
                      className="px-4.5 w-full rounded border border-stroke bg-boxdark py-3 text-white focus:border-primary focus:outline-none"
                    >
                      {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>

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

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

          {/* Footer */}
          <div className="border-t border-stroke px-6 py-4">
            <div className="flex gap-2">
              <button
                type="submit"
                disabled={isLoading}
                className="flex w-full items-center justify-center rounded-sm bg-primary px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              >
                {isLoading ? "Saving..." : "Save Price"}
              </button>
              <button
                type="button"
                onClick={() => setSidebar(false)}
                className="flex w-full items-center justify-center rounded-sm bg-danger px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              >
                Cancel
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddAdminStripePricePage;
