import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Loader2, ShieldAlert } from "lucide-react";
import { authApi } from "@/lib/auth";

export const Route = createFileRoute("/oauth-callback")({
  component: OAuthCallback,
});

function OAuthCallback() {
  const nav = useNavigate();
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const token = params.get("token");
    const err = params.get("error");
    if (err) {
      setError(params.get("detail") ? `${err}: ${params.get("detail")}` : err);
      return;
    }
    if (!token) {
      setError("Missing token");
      return;
    }
    // Persist token then load user profile
    window.localStorage.setItem("delta-terminal-token", token);
    authApi
      .me(token)
      .then((u) => {
        window.localStorage.setItem("delta-terminal-user", JSON.stringify(u));
        window.dispatchEvent(new Event("delta-auth-changed"));
        nav({ to: "/dashboard" });
      })
      .catch((e) => setError(e instanceof Error ? e.message : "Failed to load account"));
  }, [nav]);

  return (
    <div className="grid min-h-screen place-items-center px-4">
      <Card className="glass-strong w-full max-w-md p-8 text-center">
        {error ? (
          <>
            <ShieldAlert className="mx-auto mb-3 h-8 w-8 text-destructive" />
            <div className="font-display text-lg font-semibold">Sign-in failed</div>
            <p className="mt-2 text-sm text-muted-foreground break-all">{error}</p>
            <Button className="mt-4" onClick={() => nav({ to: "/login" })}>Back to sign in</Button>
          </>
        ) : (
          <>
            <Loader2 className="mx-auto mb-3 h-8 w-8 animate-spin text-primary" />
            <div className="font-display text-lg font-semibold">Completing sign-in…</div>
            <p className="mt-2 text-sm text-muted-foreground">One moment while we set up your session.</p>
          </>
        )}
      </Card>
    </div>
  );
}
