"use client";

import { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { AlertCircle, CheckCircle2, Loader2 } from "lucide-react";
import { Card } from "@/components/ui/card";
import { useAuthStore } from "@/store/auth-store";

function LinkedInCallbackContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const setUser = useAuthStore((s) => s.setUser);
  const [status, setStatus] = useState<"processing" | "success" | "error">("processing");
  const [errorMessage, setErrorMessage] = useState("");

  const code = searchParams.get("code");
  const state = searchParams.get("state");
  const error = searchParams.get("error");
  const errorDescription = searchParams.get("error_description");
  const from = searchParams.get("from") ?? "/dashboard";

  useEffect(() => {
    if (error) {
      setStatus("error");
      setErrorMessage(errorDescription ?? error);
      return;
    }

    if (!code || !state) {
      setStatus("error");
      setErrorMessage("Missing authorization code or state.");
      return;
    }

    let cancelled = false;

    (async () => {
      try {
        const res = await fetch("/api/auth/linkedin/callback", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ code, state }),
        });

        const data = (await res.json()) as {
          success?: boolean;
          user?: {
            id: string;
            name: string;
            email: string;
            initials: string;
            provider: "linkedin";
          };
          redirectTo?: string;
          error?: string;
        };

        if (!res.ok || !data.success || !data.user) {
          throw new Error(data.error ?? "LinkedIn sign-in failed");
        }

        if (!cancelled) {
          setUser(data.user);
          setStatus("success");
          setTimeout(() => {
            window.location.href = data.redirectTo ?? from;
          }, 600);
        }
      } catch (err) {
        if (!cancelled) {
          setStatus("error");
          setErrorMessage(err instanceof Error ? err.message : "LinkedIn sign-in failed");
        }
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [code, state, error, errorDescription, from, router, setUser]);

  return (
    <Card className="w-full max-w-md p-8">
      <div className="space-y-4 text-center">
        {status === "processing" && (
          <>
            <Loader2 className="mx-auto h-8 w-8 animate-spin text-brand-600" />
            <p className="font-medium text-gray-900">Signing in with LinkedIn…</p>
            <p className="text-sm text-gray-500">Verifying your account securely.</p>
          </>
        )}
        {status === "success" && (
          <>
            <CheckCircle2 className="mx-auto h-8 w-8 text-green-600" />
            <p className="font-medium text-gray-900">Signed in successfully</p>
            <p className="text-sm text-gray-500">Redirecting to your workspace…</p>
          </>
        )}
        {status === "error" && (
          <>
            <AlertCircle className="mx-auto h-8 w-8 text-red-500" />
            <p className="font-medium text-gray-900">Sign-in failed</p>
            <p className="text-sm text-gray-500">{errorMessage}</p>
            <Link
              href="/login"
              className="inline-flex items-center justify-center rounded-[var(--radius-button)] border border-gray-200 bg-white px-5 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              Back to login
            </Link>
          </>
        )}
      </div>
    </Card>
  );
}

export function LinkedInCallbackPage() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-surface p-4">
      <Suspense
        fallback={<Loader2 className="h-8 w-8 animate-spin text-brand-600" />}
      >
        <LinkedInCallbackContent />
      </Suspense>
    </div>
  );
}
