"use client";

import { Suspense, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";

export default function AcceptInvitePage() {
  return (
    <Suspense fallback={null}>
      <AcceptInviteForm />
    </Suspense>
  );
}

function AcceptInviteForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get("token") ?? "";
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const res = await fetch("/api/auth/accept-invite", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token, password }),
    });
    const data = await res.json();
    if (!res.ok) {
      setError(data.error ?? "Something went wrong.");
      setLoading(false);
      return;
    }
    const signInRes = await signIn("credentials", { email, password, redirect: false });
    setLoading(false);
    if (signInRes?.error) {
      router.push("/login");
      return;
    }
    router.push("/sites");
    router.refresh();
  }

  if (!token) {
    return (
      <div className="min-h-screen bg-bg flex items-center justify-center p-5 text-text-primary">
        This invite link is missing its token.
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-bg flex items-center justify-center p-5">
      <div className="w-full max-w-[380px] bg-bg-card border border-border rounded-2xl p-8">
        <div className="font-heading text-xl font-bold mb-1.5">Accept your invite</div>
        <div className="text-[12.5px] text-text-secondary mb-5">
          Set a password to finish joining the organization.
        </div>
        <form onSubmit={onSubmit} className="flex flex-col gap-3.5">
          <div>
            <label className="block text-xs text-text-secondary mb-1.5">
              Email (the address you were invited with)
            </label>
            <input
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[13px] font-mono outline-none"
            />
          </div>
          <div>
            <label className="block text-xs text-text-secondary mb-1.5">Set a password</label>
            <input
              type="password"
              required
              minLength={8}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[13px] outline-none"
            />
          </div>
          {error && <div className="text-[12px] text-error">{error}</div>}
          <button
            type="submit"
            disabled={loading}
            className="w-full bg-accent text-white font-bold text-[13.5px] py-2.5 rounded-lg disabled:opacity-60"
          >
            {loading ? "Joining…" : "Accept invite & sign in"}
          </button>
        </form>
      </div>
    </div>
  );
}
