"use client";

import { useEnv } from "@/app/_features/env/useEnvFile";
import {
  changePassword,
  cleanCache,
  updateEnvFileData,
} from "@/app/_services/apiAuth";
import SpinnerMini from "@/app/components/ui/SpinnerMini";
import { handleAxiosError } from "@/app/lib/utils";
import { useQueryClient } from "@tanstack/react-query";
import { useState, useEffect } from "react";

import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

const UpdateEnvFileForm = () => {
  const [isCleaning, setCleaning] = useState(false);
  const queryClient = useQueryClient();
  const { isLoading, isError, error, data } = useEnv();

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm();

  useEffect(() => {
    if (data) {
      reset({
        mail_encryption: data?.data?.MAIL_ENCRYPTION,
        mail_host: data?.data?.MAIL_HOST,
        mail_password: data?.data?.MAIL_PASSWORD,
        mail_port: data?.data?.MAIL_PORT,
        mail_username: data?.data?.MAIL_USERNAME,
        mail_form_address: data?.data?.MAIL_FROM_ADDRESS,
        neto_api_keu: data?.data?.NETOAPI_KEY,
        neto_user_name: data?.data?.NETOAPI_USERNAME,
        telesign_api_key: data?.data?.TELESIGN_API_KEY,
        telesign_customer_id: data?.data?.TELESIGN_CUSTOMER_ID,
      });
    }
  }, [data, reset]);

  async function onSubmit(data) {
    try {
      const res = await updateEnvFileData(data);

      if (res) {
        toast.success(res.message);
        queryClient.invalidateQueries({ queryKey: ["env"] });
      }
    } catch (err) {
      console.error(err);
      if (err.response) {
        toast.error(err.response.data.message);
      } else {
        toast.error("Something went wrong!");
      }
    }
  }

  async function handleCacheClean() {
    try {
      setCleaning(true);
      const res = await cleanCache();

      if (res) {
        toast.success(res.message);
        setCleaning(false);
      }
    } catch (err) {
      handleAxiosError(err);
      setCleaning(false);
    }
  }

  return (
    <form className="md:py-8 p-2 md:px-6" onSubmit={handleSubmit(onSubmit)}>
      <div className="space-y-5">
        {/* Neto Config */}
        <div className="bg-gray-100 p-4 rounded-lg space-y-4">
          <h1 className="font-serif font-medium">Neto Config</h1>
          <div className="grid sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Neto user name
              </label>
              <div className="">
                <input
                  {...register("neto_user_name")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Neto API key
              </label>
              <div className="">
                <input
                  {...register("neto_api_keu")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Telesign Config */}
        <div className="bg-gray-100 p-4 rounded-lg space-y-4">
          <h1 className="font-serif font-medium">Telesign Config</h1>
          <div className="grid sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Telesign customer ID
              </label>
              <div className="">
                <input
                  {...register("telesign_customer_id")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Telesign API key
              </label>
              <div className="">
                <input
                  {...register("telesign_api_key")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Mail Config */}
        <div className="bg-gray-100 p-4 rounded-lg space-y-4">
          <h1 className="font-serif font-medium">Mail Config</h1>
          <div className="grid sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Mail host
              </label>
              <div className="">
                <input
                  {...register("mail_host")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Mail port
              </label>
              <div className="">
                <input
                  {...register("mail_port")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Mail username
              </label>
              <div className="">
                <input
                  {...register("mail_username")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Mail password
              </label>
              <div className="">
                <input
                  {...register("mail_password")}
                  disabled={isSubmitting}
                  type="password"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Mail encryption
              </label>
              <div className="">
                <select
                  {...register("mail_encryption")}
                  disabled={isSubmitting}
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                >
                  <option value="tls">TLS</option>
                  <option value="ssl">SSL</option>
                </select>
                {/* <input
                  {...register("mail_encryption")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                /> */}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium leading-6 text-gray-900">
                Mail form address
              </label>
              <div className="">
                <input
                  {...register("mail_form_address")}
                  disabled={isSubmitting}
                  type="text"
                  className="block w-full rounded-md border bg-gray-100 border-gray-300 py-1.5 px-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div>
        <p className="text-red-600">
          <strong>Warning:</strong> Updating this content may take 15 to 30
          minutes to reflect changes. Please ensure you clear the cache after
          making updates to avoid any inconsistencies.
        </p>
        <div className="flex flex-wrap gap-3">
          <button
            type="submit"
            disabled={isSubmitting}
            className="mt-6 font-serif flex justify-center rounded-md bg-color-primary py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-color-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-color-primary px-8"
          >
            {isSubmitting ? <SpinnerMini /> : "Save/Update"}
          </button>

          <button
            type="button"
            onClick={handleCacheClean}
            className="mt-6 font-serif flex justify-center rounded-md bg-color-primary  py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-color-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-color-primary px-8"
          >
            {isCleaning ? <SpinnerMini /> : "Cache Clean"}
          </button>
        </div>
      </div>
    </form>
  );
};

export default UpdateEnvFileForm;
