"use client";

import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { signIn, getSession } from "next-auth/react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { loginSchema, type LoginInput } from "@/lib/validation/auth";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Field, Label } from "@/components/ui/Card";
import { useState } from "react";
import {
  safeRedirectPath,
  getPostAuthRedirectPath,
} from "@/lib/utils/safe-redirect";

export function LoginForm() {
  const searchParams = useSearchParams();
  const explicitCallback = searchParams.get("callbackUrl");
  const callbackUrl = safeRedirectPath(explicitCallback);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

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

  async function onSubmit(data: LoginInput) {
    setLoading(true);
    setError(null);

    const result = await signIn("credentials", {
      email: data.email,
      password: data.password,
      redirect: false,
    });

    setLoading(false);

    if (result?.error) {
      setError("Invalid email or password");
      return;
    }

    // Full navigation so the session cookie is always sent on the next
    // request. Soft router.push + refresh races middleware in production
    // and causes an endless login ↔ dashboard reload loop.
    if (explicitCallback) {
      window.location.assign(callbackUrl);
      return;
    }

    const session = await getSession();
    const path = getPostAuthRedirectPath({
      role: session?.user?.role,
      workspaceId: session?.user?.workspaceId ?? null,
    });
    window.location.assign(path);
  }

  async function handleGoogleSignIn() {
    await signIn("google", { callbackUrl });
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Field>
        <Label htmlFor="email">Work email</Label>
        <Input
          id="email"
          type="email"
          placeholder="you@company.com"
          {...register("email")}
        />
        {errors.email && (
          <p className="mt-1 text-xs text-danger">{errors.email.message}</p>
        )}
      </Field>

      <Field>
        <Label htmlFor="password">Password</Label>
        <Input
          id="password"
          type="password"
          placeholder="••••••••"
          {...register("password")}
        />
        {errors.password && (
          <p className="mt-1 text-xs text-danger">{errors.password.message}</p>
        )}
      </Field>

      <div className="mb-[18px] flex items-center justify-between text-[12.5px]">
        <label className="flex items-center gap-1.5">
          <input type="checkbox" className="rounded" />
          Remember me
        </label>
        <Link
          href="/forgot-password"
          className="font-semibold text-primary hover:underline"
        >
          Forgot password?
        </Link>
      </div>

      {error && (
        <p className="mb-3 text-sm text-danger">{error}</p>
      )}

      <Button type="submit" className="w-full" loading={loading}>
        {loading ? "Signing in…" : "Log in"}
      </Button>

      <div className="my-5 flex items-center gap-2.5 text-xs text-muted">
        <div className="h-px flex-1 bg-border" />
        or continue with
        <div className="h-px flex-1 bg-border" />
      </div>

      <div className="flex gap-2.5">
        <Button
          type="button"
          variant="outline"
          className="flex-1 border-border text-text"
          onClick={handleGoogleSignIn}
        >
          Google
        </Button>
      </div>
    </form>
  );
}
