"use client";

import { useState } from "react";
import Image from "next/image";
import Input from "../../ui/CustomInput";
import Button from "../../ui/Button";
import { FiMail, FiLock, FiEye, FiEyeOff } from "react-icons/fi";
import { useModal } from "../../../lib/modal-system/ModalContext";
import { useAppForm } from "../../../hooks/useAppForm";
import {
  loginSchema,
  LoginSchema,
} from "../../../hooks/features/auth/login/schema";
import useLogin from "../../../hooks/features/auth/login/useLogin";
import { AxiosError } from "axios";
import { formatStringWithUppercase } from "../../../utils/helper";
import { useRouter } from "next/navigation";
import useResendEmail from "../../../hooks/features/auth/resend-email/useResendEmail";
import { MODAL_TYPES } from "../../../lib/modal-system/ModalRegistery";

export default function LoginForm() {
  const [showPassword, setShowPassword] = useState(false);

  const { openModal, closeModal } = useModal();
  const { login } = useLogin();
  const router = useRouter();
  const { handleResendEmail } = useResendEmail();

  const [loading, setLoading] = useState<boolean>(false);

  const { register, handleSubmit, errors, reset, setError } =
    useAppForm<LoginSchema>({
      defaultValues: {
        email: "",
        password: "",
      },
      schema: loginSchema,
      onSubmit: async (data) => {
        try {
          setLoading(true);

          const res = await login(data);
          const { user, emailVerified } = res.data;
          if (emailVerified) {
            reset();
            closeModal();

            if (user.role[0] === "user") {
              window.location.replace("/dashboard");
            } else {
              window.location.replace("/admin");
            }
          } else {
            try {
              await handleResendEmail({ email: user.email });
            } catch {
              // Resend failing should not block opening CHECK_EMAIL —
              // the user can retry from there with the 60s cooldown.
            }

            reset();
            openModal(MODAL_TYPES.CHECK_EMAIL_FOR_VERIFICATION, {
              email: user.email,
            });
          }
        } catch (error) {
          const axiosError = error as AxiosError<{
            message?: string;
            errors?: Record<string, string[]>;
          }>;

          const fieldErrors = axiosError?.response?.data?.errors;

          if (fieldErrors) {
            Object.entries(fieldErrors).forEach(([field, messages]) => {
              setError(field as keyof LoginSchema, {
                type: "server",
                message: formatStringWithUppercase(messages[0]),
              });
            });
          }
        } finally {
          setLoading(false);
        }
      },
    });

  return (
    <>
      <Image
        src="/images/logo.svg"
        alt="KleboAI"
        width={90}
        height={70}
        priority
        className="mx-auto h-auto"
      />

      <h2 className="mt-7.5 text-center font-heading text-xl font-semibold text-heading md:text-2xl">
        Sign In
      </h2>

      <p className="mt-2 text-center font-body text-base md:text-lg text-text">
        Welcome back to Klebo AI
      </p>

      <div className="mt-8 space-y-3 2xl:space-y-5">
        <div>
          <Input
            label="Email"
            icon={<FiMail />}
            placeholder="Enter Your Email"
            register={register("email")}
            error={errors.email?.message}
          />
        </div>

        <div>
          <Input
            label="Password"
            type={showPassword ? "text" : "password"}
            icon={<FiLock />}
            placeholder="Enter Your Password"
            register={register("password")}
            error={errors.password?.message}
            rightIcon={
              <button
                type="button"
                onClick={() => setShowPassword((prev) => !prev)}
                className="text-link-1 transition hover:opacity-80 cursor-pointer"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                {showPassword ? <FiEyeOff size={18} /> : <FiEye size={18} />}
              </button>
            }
          />
        </div>
      </div>

      <div className="mt-4 flex items-center justify-between gap-3">
        <label className="flex cursor-pointer items-center gap-2 font-body text-sm text-heading">
          <input type="checkbox" className="h-4 w-4 accent-[#8B5CF6]" />
          Remember Me
        </label>

        <button
          type="button"
          onClick={() => {
            openModal("FORGOT_PASSWORD", {});
          }}
          className="font-body text-sm font-medium text-link-1 cursor-pointer"
        >
          Forgot Password?
        </button>
      </div>

      <Button loading={loading} className="mt-6 w-full" onClick={handleSubmit}>
        Sign In
      </Button>

      <p className="mt-6 text-center font-body text-sm text-heading">
        Don&apos;t have an account?
        <button
          type="button"
          onClick={() => openModal("SIGNUP", {})}
          className="ml-1 font-medium text-link-1 cursor-pointer"
        >
          Sign Up
        </button>
      </p>
    </>
  );
}
