"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { loginViaAccessKeys } from "@/apicalls/login/login";
import { z } from "zod";

const loginSchema = z.object({
  email: z.string().email("Invalid email address"),
  password: z.string().min(5, "Password must be at least 5 characters"),
  remember_me: z.boolean().optional().default(false),
});

type LoginFormData = {
  email: string;
  password: string;
  remember_me?: boolean;
};

function Login() {
  // Open transition for form login
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [jsonText, setJsonText] = useState<string | null>(null);

  const Router = useRouter();

  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
  });

  const onSubmit = async (data: LoginFormData) => {
    try {
      startTransition(() => {
        try {
          loginViaAccessKeys({
            accessKey: data.email,
            password: data.password,
            rememberMe: false,
          })
            .then((result: any) => {
              const dataResponse = result?.data;
              if (dataResponse?.access_token) {
                setJsonText(JSON.stringify(dataResponse));
                setTimeout(() => {
                  Router.push("/auth/select");
                }, 2000);
              }
              return dataResponse;
            })
            .catch(() => {});
        } catch (error) {}
      });
    } catch (error) {
      console.error("Login error:", error);
      setError("An error occurred during login");
    }
  };
  return (
    <>
      <div className="flex h-full min-h-[inherit] flex-col items-center justify-center gap-4">
        <div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
          <h2 className="mb-6 text-center text-2xl font-bold text-gray-900">
            Login
          </h2>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div>
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-700"
              >
                Email
              </label>
              <input
                {...register("email")}
                type="email"
                id="email"
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-indigo-500"
              />
              {errors.email && (
                <p className="mt-1 text-sm text-red-600">
                  {errors.email.message}
                </p>
              )}
            </div>

            <div>
              <label
                htmlFor="password"
                className="block text-sm font-medium text-gray-700"
              >
                Password
              </label>
              <input
                {...register("password")}
                type="password"
                id="password"
                className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-indigo-500"
              />
              {errors.password && (
                <p className="mt-1 text-sm text-red-600">
                  {errors.password.message}
                </p>
              )}
            </div>

            {error && (
              <div className="rounded-md bg-red-50 p-4">
                <p className="text-sm text-red-700">{error}</p>
              </div>
            )}

            <button
              type="submit"
              disabled={isPending}
              className="w-full rounded-md bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50"
            >
              {isPending ? "Logging in..." : "Login"}
            </button>
          </form>
        </div>

        {jsonText && (
          <div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
            <h2 className="mb-4 text-center text-xl font-bold text-gray-900">
              Response Data
            </h2>
            <div className="space-y-2">
              {Object.entries(JSON.parse(jsonText)).map(([key, value]) => (
                <div key={key} className="flex items-start gap-2">
                  <strong className="text-gray-700">{key}:</strong>
                  <span className="text-gray-600">
                    {typeof value === "object"
                      ? JSON.stringify(value)
                      : value?.toString() || "N/A"}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </>
  );
}

export default Login;
