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

import { FormErrorMessages } from "@/constants/Texts";
import { useLoginQuery } from "@/hooks/queries";
import { ILoginCredentials } from "@/lib/api";
import { COOKIE_KEYS } from "@/lib/shared/cookies";
import { cn } from "@/lib/utils";
import { useIsMutating } from "@tanstack/react-query";
import Cookies from "js-cookie";
import { useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import InputGroup from "../FormElements/InputGroup";

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

  const onSubmit: SubmitHandler<ILoginCredentials> = (data) => {
    mutate({
      ...data,
      device_token: Cookies.get(COOKIE_KEYS.device_token) ?? "",
    });
  };
  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"
          disabled={!!isMutating}
          className={cn(
            "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 && "cursor-not-allowed bg-primary/50",
          )}
        >
          {isMutating ? (
            <div className="h-5 w-5 animate-spin rounded-full border-b-2 border-gray-1"></div>
          ) : (
            "Sign in"
          )}
        </button>
      </div>
    </form>
  );
}
