import { Dialog, Transition } from "@headlessui/react";
import { XMarkIcon } from "@heroicons/react/24/solid";
import { InteractiveButton } from "Components/InteractiveButton";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Context/Global";
import TreeSDK from "Utils/TreeSDK";
import { Fragment, useContext, useEffect, useState } from "react";

export default function EditSettingButton({ value, setting_key, afterEdit }) {
  const [open, setOpen] = useState(false);
  const { dispatch: authDispatch } = useContext(AuthContext);
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const [loading, setLoading] = useState(false);
  const [newValue, setNewValue] = useState("");

  useEffect(() => {
    setNewValue(value);
  }, [value]);

  async function editSetting() {
    setLoading(true);
    try {
      const treeSdk = new TreeSDK();
      await treeSdk.updateWhere(
        "setting",
        { setting_key },
        { setting_value: newValue }
      );
      setOpen(false);
      afterEdit();
      showToast(globalDispatch, "settings updated");
    } catch (err) {
      tokenExpireError(authDispatch, err.message);
      showToast(globalDispatch, err.message, 5000, "error");
    }
    setLoading(false);
  }

  return (
    <>
      <button
        className="bg-primary-black rounded-md px-2 py-1 text-sm font-medium text-white"
        onClick={() => setOpen(true)}
      >
        Edit
      </button>
      <Transition appear show={open} as={Fragment}>
        <Dialog
          as="div"
          className="relative z-[50] sm:z-[50]"
          onClose={() => setOpen(false)}
        >
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-[#1f1d1a] bg-opacity-25" />
          </Transition.Child>

          <div className="fixed inset-0 overflow-y-auto">
            <div className="flex min-h-full items-center justify-center p-4 text-center">
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 scale-95"
                enterTo="opacity-100 scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 scale-100"
                leaveTo="opacity-0 scale-95"
              >
                <Dialog.Panel className="bg-brown-main-bg bg-brown-main-bg w-full max-w-md transform overflow-hidden rounded-md p-6 text-left align-middle text-base shadow-xl transition-all">
                  <div className="flex items-center justify-between">
                    <Dialog.Title
                      as="h3"
                      className="text-lg font-semibold leading-6 text-gray-900"
                    >
                      Edit
                    </Dialog.Title>
                    <button onClick={() => setOpen(false)} type="button">
                      <XMarkIcon className="h-6 w-6" />
                    </button>
                  </div>

                  <input
                    className={`focus:shadow-outline mt-3 w-[100px] appearance-none rounded border border-[#1f1d1a] bg-transparent px-3 py-2 leading-tight text-[#1d1f1a] shadow   focus:outline-none sm:w-[180px] ${
                      false ? "border-red-500" : ""
                    }`}
                    value={newValue}
                    onChange={(e) => setNewValue(e.target.value)}
                    placeholder="Type a number"
                  />

                  <div className="mt-6 grid grid-cols-2 gap-4">
                    <button
                      className="font-iowan rounded-lg border border-[#1f1d1a] py-2 text-center"
                      type="button"
                      onClick={() => setOpen(false)}
                    >
                      Cancel
                    </button>
                    <InteractiveButton
                      loading={loading}
                      disabled={loading}
                      onClick={editSetting}
                      className="disabled:bg-disabledblack bg-primary-black rounded-lg py-2 text-center font-semibold text-white transition-colors duration-100"
                    >
                      Save
                    </InteractiveButton>
                  </div>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition>
    </>
  );
}
