"use client";
import { PasswordIcon, UserIcon } from "@/assets/icons";

import { useLoginQuery } from "@/hooks/queries";
import { ILoginCredentials } from "@/lib/api";
import { useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import InputGroup from "../FormElements/InputGroup";

import { FormErrorMessages } from "@/constants/Texts";
import { useIsMutating } from "@tanstack/react-query";

export default function SigninWithPassword() {
  const isMutating = useIsMutating();
  const [passwordFieldInputType, setPasswordFieldInputType] = useState<
    "password" | "text"
  >("password");
  const { handleSubmit, control, reset, register } =
    useForm<ILoginCredentials>();
  const { mutate } = useLoginQuery(reset);

  const onSubmit: SubmitHandler<ILoginCredentials> = (data) => {
    mutate(data);
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <InputGroup
        type="username"
        disabled={!!isMutating}
        {...register("username", {
          required: {
            value: true,
            message: FormErrorMessages.required,
          },
        })}
        label="Username"
        className="mb-4 [&_input]:py-[15px]"
        placeholder="Enter your Username"
        name="username"
        icon={<UserIcon />}
      />

      <InputGroup
        type={passwordFieldInputType}
        disabled={!!isMutating}
        {...register("password", {
          required: {
            value: true,
            message: FormErrorMessages.required,
          },
        })}
        label="Password"
        className="mb-5 [&_input]:py-[15px]"
        placeholder="Enter your password"
        name="password"
        icon={
          <PasswordIcon
            className="cursor-pointer"
            onClick={() => {
              setPasswordFieldInputType(
                passwordFieldInputType === "password" ? "text" : "password",
              );
            }}
          />
        }
      />

      <div className="mb-4.5">
        <button
          type="submit"
          className="flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg bg-primary p-4 font-medium text-white transition hover:bg-opacity-90"
        >
          {isMutating ? (
            <div className="h-5 w-5 animate-spin rounded-full border-b-2 border-gray-1"></div>
          ) : (
            "Sign in"
          )}
        </button>
      </div>
    </form>
  );
}
