"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";
import { ThemeToggleSwitch } from "../Layouts/header/theme-toggle";
import { Button } from "../ui-elements/button";

export default function SigninWithPassword() {
  const isMutating = useIsMutating();
  const [passwordFieldInputType, setPasswordFieldInputType] = useState<
    "password" | "text"
  >("password");
  const {
    handleSubmit,
    reset,
    register,
    formState: { errors },
  } = 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)} className="mt-5">
      <div className="absolute right-0 top-7 hidden sm:block">
        <ThemeToggleSwitch />
      </div>
      <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"
        errors={errors}
        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"
        errors={errors}
        icon={
          <button
            type="button"
            onClick={() => {
              setPasswordFieldInputType(
                passwordFieldInputType === "password" ? "text" : "password",
              );
            }}
            className="absolute right-4.5 top-1/2 z-10 flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded text-dark-5 transition hover:text-primary dark:text-white/75 [&>svg]:!static [&>svg]:!size-5 [&>svg]:!translate-y-0"
            aria-label={
              passwordFieldInputType === "password"
                ? "Show password"
                : "Hide password"
            }
          >
            <PasswordIcon className="pointer-events-none" />
          </button>
        }
      />

      <div className="mb-4.5">
        <Button
          label={
            isMutating ? (
              <div className="h-5 w-5 animate-spin rounded-full border-b-2 border-gray-1"></div>
            ) : (
              "Sign in"
            )
          }
          variant="primary"
          shape="rounded"
          size="small"
          type="submit"
          disabled={!!isMutating}
          className={cn(
            "shadow-theme-xs w-full rounded-xl bg-gradient-to-r from-primary to-primary/85 p-4 font-semibold transition-all duration-300 hover:-translate-y-0.5 hover:opacity-95",
            isMutating && "cursor-not-allowed opacity-70 hover:translate-y-0",
          )}
        />
      </div>
    </form>
  );
}
