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

const AddAdminStripeProductPage = ({ onSuccess = null, setSidebar }) => {
  let sdk = new MkdSDK();
  const [isLoading, setIsLoading] = useState(false);

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

  const navigate = useNavigate();

  const schema = yup
    .object({
      name: yup.string().required(),
      description: yup.string().nullable(),
    })
    .required();

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

  const onSubmit = async (data) => {
    try {
      setIsLoading(true);
      const result = await sdk.addStripeProduct({
        name: data.name,
        description: data.description,
      });
      if (!result?.error) {
        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];
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
    } catch (error) {
      console.log("Error", error);
      tokenExpireError(dispatch, error.message);
    } finally {
      setIsLoading(false);
    }
  };

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

  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-box"
                className="text-xl text-primary"
              />
              <h3 className="text-xl font-medium text-white">Add Product</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">
              {/* 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 product name"
                />
                {errors.name && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.name.message}
                  </p>
                )}
              </div>

              {/* Description Input */}
              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Description
                </label>
                <textarea
                  {...register("description")}
                  className="px-4.5 w-full rounded border border-stroke bg-boxdark py-3 text-white focus:border-primary focus:outline-none"
                  placeholder="Enter product description"
                  rows={4}
                />
                {errors.description && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.description.message}
                  </p>
                )}
              </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 Product"}
              </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 AddAdminStripeProductPage;
