"use client";

import { useState, type FormEvent } from "react";
import Link from "next/link";
import { GoogleOAuthProvider } from "@react-oauth/google";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/ui/password-input";
import { AuthDivider } from "@/components/auth/auth-divider";
import { GoogleAuthButton } from "@/components/auth/google-auth-button";

const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? "";

export default function LoginPage() {
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);
    setIsSubmitting(true);

    const formData = new FormData(event.currentTarget);

    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: formData.get("email"),
          password: formData.get("password"),
        }),
      });

      if (!res.ok) {
        const body = await res.json().catch(() => null);
        setError(body?.message ?? "Incorrect email or password.");
        setIsSubmitting(false);
        return;
      }

      // Full navigation (not router.push+refresh) — every Server Component
      // that reads the auth cookie (e.g. the navbar's user menu) must see the
      // freshly-set session, and a client-side transition can race with the
      // cookie write, leaving the user stuck on this page despite a
      // successful login (matches the plain <form> POST logout already uses).
      window.location.href = "/";
    } catch {
      setError("Unable to reach the server. Please check your connection and try again.");
      setIsSubmitting(false);
    }
  }

  return (
    <div className="mx-auto flex min-h-[70vh] max-w-md flex-col justify-center px-6 py-12">
      <h1 className="text-2xl font-semibold">Log in to Kolaborativ</h1>
      <p className="mt-1 text-sm text-kolabora-neutral-dark/70">
        Don&apos;t have an account?{" "}
        <Link href="/register" className="font-medium text-kolabora-primary">
          Sign up here
        </Link>
      </p>

      <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-4">
        <label className="flex flex-col gap-1 text-sm font-medium">
          Email
          <Input type="email" name="email" required />
        </label>

        <label className="flex flex-col gap-1 text-sm font-medium">
          Password
          <PasswordInput name="password" required />
        </label>

        {error && <p className="text-sm text-red-600">{error}</p>}

        <Button type="submit" loading={isSubmitting} className="mt-2">
          Log In
        </Button>
      </form>

      {GOOGLE_CLIENT_ID && (
        <>
          <AuthDivider />

          <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
            <GoogleAuthButton label="Continue with Google" onError={setError} />
          </GoogleOAuthProvider>
        </>
      )}
    </div>
  );
}
