"use client";

import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { useTransition } from "react";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "@/components/ui/form";
import { googleSignIn, login } from "@/actions/authActions";
import { loginSchemaType, loginSchema } from "@/schemas/auth.schema";
import { FormError } from "@/components/form/FormError";
import { FormSuccess } from "@/components/form/FormSuccess";
import { useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

const LoginPage: React.FC = () => {
  const { update, data: session } = useSession();
  const params = useSearchParams();
  const urlError =
    params.get("error") === "OAuthAccountNotLinked"
      ? "Email already in use with different provider!"
      : "";
  const [error, setError] = useState<string | undefined>("");
  const [success, setSuccess] = useState<string | undefined>("");
  const [twoFactor, setTwoFactor] = useState<boolean>(false);
  const [isPending, startTransition] = useTransition();

  const form = useForm<loginSchemaType>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: "",
      password: "",
      code: "",
    },
  });

  const router = useRouter();
  const onSubmit = (values: loginSchemaType) => {
    setError("");
    setSuccess("");
    startTransition(() => {
      login(values)
        .then(async (data) => {
          if (data?.error) {
            setError(data.error);
          }
          if (data?.success && data.success) {
            form.reset();
            setSuccess(data.success);
            await update();
            router.push(data.redirectUrl);
          }
          if (data?.twoFactor) {
            setTwoFactor(true);
          }
        })
        .catch(() => {
          setError("Something went wrong!");
        });
    });
  };

  return (
    <>
      <h1 className="mb-6 text-center text-2xl font-bold">Login</h1>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
          {!twoFactor ? (
            <>
              <FormField
                control={form.control}
                
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email:</FormLabel>
                    <FormControl>
                      <Input
                        type="email"
                        id="email"
                        placeholder="Enter your email"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Password:</FormLabel>
                    <FormControl>
                      <Input
                        type="password"
                        id="password"
                        placeholder="Enter your password"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </>
          ) : (
            <>
              <FormField
                control={form.control}
                name="code"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>2FA Code:</FormLabel>
                    <FormControl>
                      <Input
                        disabled={isPending}
                        type="text"
                        id="code"
                        placeholder="Enter your 2FA code"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="mt-6 text-center">
                <Button
                  type="button"
                  variant="ghost"
                  onClick={() => {
                    setTwoFactor(false);
                    form.reset();
                  }}
                  className="text-sm text-primary hover:underline"
                >
                  Sign in with another account
                </Button>
              </div>
            </>
          )}

          {!twoFactor && (
            <div className="text-right text-sm">
              <Link
                href="/auth/forgot-password"
                className="text-primary hover:underline"
              >
                Forgot password?
              </Link>
            </div>
          )}

          <FormError message={error || urlError} />
          <FormSuccess message={success} />

          <Button
            type="submit"
            className="w-full rounded-md py-2 text-white"
            disabled={isPending}
          >
            {
              twoFactor
                ? isPending
                  ? "Verifying..." // Fixed text
                  : "Verify Code" // Fixed text
                : isPending
                  ? "Logging in..." // Fixed text
                  : "Login" // Fixed text
            }
          </Button>
        </form>
      </Form>

      {!twoFactor && (
        <>
          <div className="relative my-6">
            <div className="absolute inset-0 flex items-center">
              <span className="w-full border-t" />
            </div>
            <div className="relative flex justify-center text-xs uppercase">
              <span className="bg-white px-2 text-muted-foreground">
                Or continue with
              </span>
            </div>
          </div>

          <form action={googleSignIn}>
            <Button
              variant="outline"
              type="submit"
              className="mt-4 w-full rounded-md py-2"
            >
              <svg
                className="mr-2 h-4 w-4"
                aria-hidden="true"
                focusable="false"
                data-prefix="fab"
                data-icon="google"
                role="img"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 488 512"
              >
                <path
                  fill="currentColor"
                  d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"
                ></path>
              </svg>
              Sign in with Google
            </Button>
          </form>

          <p className="mt-4 text-center">
            Don&apos;t have an account?{" "}
            <Link
              href="/auth/register"
              className="text-primary hover:underline"
            >
              Register
            </Link>
          </p>
        </>
      )}
    </>
  );
};

export default LoginPage;
