"use client";

import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { storeAuthTokens } from "@/lib/api";

type ApiResponse<T> = {
  data: T;
  meta: { timestamp: string; version: "v1" };
  error: null | { message: string; code?: string };
};

type SocialAuthData = {
  user: { id: string; email: string; fullName?: string; emailVerified?: boolean };
  accessToken?: string;
  refreshToken?: string;
  next?: string;
};

function decodeProvider(state: string | null) {
  if (!state) return "";
  try {
    const [body] = state.split(".");
    const normalized = body.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(body.length / 4) * 4, "=");
    const json = JSON.parse(atob(normalized)) as { provider?: string };
    return json.provider === "apple" || json.provider === "google" ? json.provider : "";
  } catch {
    return "";
  }
}

function SocialCallbackContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [status, setStatus] = useState<"loading" | "success" | "error">("loading");
  const [message, setMessage] = useState("Completing sign in...");

  useEffect(() => {
    const error = searchParams.get("error");
    const code = searchParams.get("code");
    const state = searchParams.get("state");
    const provider = decodeProvider(state);

    if (error) {
      setStatus("error");
      setMessage(error === "access_denied" ? "You declined social sign in." : `Provider returned an error: ${error}`);
      return;
    }
    if (!provider || !code || !state) {
      setStatus("error");
      setMessage("Social sign in callback is missing required data.");
      return;
    }

    fetch(`/api/auth/social/${provider}/callback`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ code, state }),
    })
      .then(async (res) => {
        const payload = (await res.json()) as ApiResponse<SocialAuthData>;
        if (!res.ok || payload.error) throw new Error(payload.error?.message ?? "Social sign in failed.");
        storeAuthTokens({
          user: payload.data.user,
        });
        setStatus("success");
        setMessage(`Signed in as ${payload.data.user.email}.`);
        setTimeout(() => router.replace(payload.data.next || "/app"), 800);
      })
      .catch((err: Error) => {
        setStatus("error");
        setMessage(err.message || "Social sign in failed.");
      });
  }, [router, searchParams]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-6">
      <div className="glass-panel rounded-2xl p-10 text-center max-w-sm w-full shadow-lg">
        {status === "loading" && (
          <>
            <div className="h-12 w-12 rounded-full border-4 border-primary border-t-transparent animate-spin mx-auto mb-4" />
            <p className="text-sm text-muted-foreground">{message}</p>
          </>
        )}
        {status === "success" && (
          <>
            <div className="h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto mb-4">
              <svg className="h-6 w-6 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <p className="text-sm font-semibold text-foreground">Signed in</p>
            <p className="text-xs text-muted-foreground mt-1">{message}</p>
          </>
        )}
        {status === "error" && (
          <>
            <div className="h-12 w-12 rounded-full bg-red-500/10 flex items-center justify-center mx-auto mb-4">
              <svg className="h-6 w-6 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </div>
            <p className="text-sm font-semibold text-foreground">Sign in failed</p>
            <p className="text-xs text-muted-foreground mt-1">{message}</p>
            <button onClick={() => router.replace("/login")} className="mt-4 text-xs text-primary hover:underline">
              Back to sign in
            </button>
          </>
        )}
      </div>
    </div>
  );
}

export default function SocialCallbackPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen flex items-center justify-center bg-background">
          <div className="h-12 w-12 rounded-full border-4 border-primary border-t-transparent animate-spin" />
        </div>
      }
    >
      <SocialCallbackContent />
    </Suspense>
  );
}
