/* eslint-disable react-hooks/set-state-in-effect */
import { useEffect, useState } from "react";
import { saveMerchant, getMerchant, clearDevice } from "../../utils/storage";
import { useNavigate } from "@tanstack/react-router";

export default function SettingsFeature() {
  const navigate = useNavigate();

  const [form, setForm] = useState<MerchantForm>({
    merchantName: "",
    tower: "",
    floor: "",
    unit: "",
    credential: "",
  });
  const [loading, setLoading] = useState<boolean>(false);

  function isObjectValueDifferent(a: MerchantForm, b: MerchantForm): boolean {
    return (Object.keys(a) as (keyof MerchantForm)[]).some(
      (key) => a[key] !== b[key],
    );
  }

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const { name, value } = e.target;
    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    const merchant = getMerchant();

    if (merchant) {
      const isDifferent = isObjectValueDifferent(merchant, form);
      if (isDifferent) {
        clearDevice(); // reset device kalau merchant berubah
      }
    }

    setLoading(true);
    saveMerchant(form);

    setTimeout(() => {
      setLoading(false);
      navigate({ to: "/" });
    }, 200);
  }

  useEffect(() => {
    const merchant = getMerchant();
    if (merchant) {
      setForm(merchant);
    }
  }, []);

  const isFormValid =
    form.merchantName?.trim() &&
    form.tower?.trim() &&
    form.floor?.trim() &&
    form.unit?.trim();

  return (
    <form onSubmit={handleSubmit} className="p-4">
      <div className="flex flex-col gap-4">
        <div>
          <label className="mb-1 text-neutral-900 block font-semibold">
            Merchant Name
          </label>
          <input
            name="merchantName"
            value={form.merchantName}
            onChange={handleChange}
            className="p-2 border border-neutral-200 w-full rounded-md"
          />
        </div>

        <div>
          <label className="mb-1 text-neutral-900 block font-semibold">
            Tower
          </label>
          <input
            name="tower"
            value={form.tower}
            onChange={handleChange}
            className="p-2 border border-neutral-200 w-full rounded-md"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="mb-1 text-neutral-900 block font-semibold">
              Floor
            </label>
            <input
              name="floor"
              value={form.floor}
              onChange={handleChange}
              className="p-2 border border-neutral-200 w-full rounded-md"
            />
          </div>

          <div>
            <label className="mb-1 text-neutral-900 block font-semibold">
              Unit
            </label>
            <input
              name="unit"
              value={form.unit}
              onChange={handleChange}
              className="p-2 border border-neutral-200 w-full rounded-md"
            />
          </div>

          <div>
            <label className="mb-1 text-neutral-900 block font-semibold">
              Credential
            </label>
            <input
              name="credential"
              value={form.credential}
              onChange={handleChange}
              className="p-2 border border-neutral-200 w-full rounded-md"
            />
          </div>
        </div>
      </div>

      <button
        type="submit"
        disabled={!isFormValid || loading}
        className="
          w-full py-2 rounded-lg mt-8 text-white cursor-pointer
          bg-orange-500
          disabled:bg-neutral-400
          disabled:cursor-not-allowed
        "
      >
        {loading ? "Saving..." : "Save"}
      </button>
    </form>
  );
}
