"use client";

import type {Route} from "next";
import Link from "next/link";
import {useRouter, useSearchParams} from "next/navigation";
import {useState, useTransition} from "react";
import {zodResolver} from "@hookform/resolvers/zod";
import {useForm} from "react-hook-form";
import {signIn} from "next-auth/react";
import {z} from "zod";
import {Mail, Lock, ArrowRight, Loader2} from "lucide-react";
import {AuthCard} from "@/components/auth/auth-card";
import {Alert} from "@/components/ui/alert";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import {APP_ROUTES} from "@/lib/constants/routes";
import {signInSchema} from "@/lib/validations/auth";

type SignInFormProps = {
  locale: string;
};

type FormValues = z.infer<typeof signInSchema>;

export function SignInForm({locale}: SignInFormProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const callbackUrl = searchParams.get("callbackUrl") ?? `/${locale}`;
  const form = useForm<FormValues>({
    resolver: zodResolver(signInSchema),
    defaultValues: {
      email: "",
      password: ""
    }
  });

  const onSubmit = (values: FormValues) => {
    setErrorMessage(null);

    startTransition(async () => {
      const result = await signIn("credentials", {
        email: values.email,
        password: values.password,
        redirect: false,
        callbackUrl
      });

      if (!result || result.error) {
        setErrorMessage("Invalid email or password.");
        return;
      }

      router.push((result.url ?? callbackUrl) as Route);
      router.refresh();
    });
  };

  return (
    <AuthCard
      locale={locale}
      title="Welcome back"
      description="Sign in to your account to continue."
      footer={
        <div className="flex items-center justify-between text-sm">
          <Link
            className="text-indigo-600 hover:text-indigo-700 font-medium transition-colors"
            href={`/${locale}${APP_ROUTES.signUp}` as Route}
          >
            Create account
          </Link>
          <Link
            className="text-gray-500 hover:text-gray-700 transition-colors"
            href={`/${locale}${APP_ROUTES.forgotPassword}` as Route}
          >
            Forgot password?
          </Link>
        </div>
      }
    >
      <form className="space-y-5" onSubmit={form.handleSubmit(onSubmit)}>
        {/* Email */}
        <div className="space-y-1.5">
          <Label className="text-gray-700 font-medium" htmlFor="email">Email address</Label>
          <div className="relative">
            <Mail className="pointer-events-none absolute start-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <Input
              id="email"
              type="email"
              className="ps-10 rounded-lg border-gray-200 focus:ring-indigo-500 focus:border-indigo-300 h-11"
              placeholder="you@example.com"
              {...form.register("email")}
            />
          </div>
          {form.formState.errors.email ? (
            <p className="text-xs text-red-600">{form.formState.errors.email.message}</p>
          ) : null}
        </div>

        {/* Password */}
        <div className="space-y-1.5">
          <Label className="text-gray-700 font-medium" htmlFor="password">Password</Label>
          <div className="relative">
            <Lock className="pointer-events-none absolute start-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <Input
              id="password"
              type="password"
              className="ps-10 rounded-lg border-gray-200 focus:ring-indigo-500 focus:border-indigo-300 h-11"
              placeholder="••••••••"
              {...form.register("password")}
            />
          </div>
          {form.formState.errors.password ? (
            <p className="text-xs text-red-600">{form.formState.errors.password.message}</p>
          ) : null}
        </div>

        {errorMessage ? (
          <Alert className="border-red-200 bg-red-50 text-red-700 text-sm">{errorMessage}</Alert>
        ) : null}

        <Button
          className="w-full gap-2 bg-indigo-600 hover:bg-indigo-700 rounded-lg py-3 h-11 text-base font-semibold shadow-sm shadow-indigo-200"
          disabled={isPending}
          type="submit"
        >
          {isPending ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              Signing in...
            </>
          ) : (
            <>
              Sign in
              <ArrowRight className="h-4 w-4" />
            </>
          )}
        </Button>
      </form>
    </AuthCard>
  );
}
