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

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

import { FormErrorMessages } from "@/constants/Texts";

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

  const onSubmit: SubmitHandler<ILoginCredentials> = (data) => {
    mutate(data);
    reset();
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <InputGroup
        type="username"
        {...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}
        {...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"
        >
          Sign In
        </button>
      </div>
    </form>
  );
}
