import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { Loader2, AlertCircle, CheckCircle2 } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

export const Route = createFileRoute("/ebay-callback")({
  head: () => ({ meta: [{ title: "Connecting eBay — Securing your store" }] }),
  component: EbayCallback,
});

type Status = "loading" | "success" | "error";

function EbayCallback() {
  const ranRef = useRef(false);
  const [status, setStatus] = useState<Status>("loading");
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (ranRef.current) return;
    ranRef.current = true;

    const code = new URLSearchParams(window.location.search).get("code");
    if (!code) {
      setStatus("error");
      setError("Missing authorization code from eBay.");
      return;
    }

    (async () => {
      try {
        const { data, error } = await supabase.functions.invoke("ebay-oauth-exchange", {
          body: { code },
        });

        if (error) {
          console.error("Full eBay OAuth error response:", error);
          let message = error.message || "Connection failed";

          if ((error as any).context) {
            try {
              const ctx =
                typeof (error as any).context === "string"
                  ? JSON.parse((error as any).context)
                  : (error as any).context;
              console.error("Parsed error context:", ctx);
              message =
                ctx?.message ||
                ctx?.error ||
                ctx?.error_description ||
                message;
            } catch (parseErr) {
              console.error("Could not parse error context:", (error as any).context);
            }
          }

          throw new Error(message);
        }

        console.log("eBay OAuth exchange response:", data);
        toast.success("Store connected successfully!");
        setStatus("success");
        window.location.href = "/dashboard";
      } catch (err: any) {
        console.error("eBay OAuth exchange failed:", err);
        setStatus("error");
        setError(err?.message ?? "Failed to connect your eBay store.");
      }
    })();
  }, []);

  return (
    <div className="dark min-h-screen flex flex-col items-center justify-center bg-background text-foreground px-4 text-center">
      {status === "loading" && (
        <>
          <Loader2 className="h-10 w-10 animate-spin mb-6 text-primary" />
          <h1 className="text-2xl font-semibold">Securing your store connection...</h1>
          <p className="mt-3 text-sm text-muted-foreground">
            Please wait while we finalize your eBay authorization.
          </p>
        </>
      )}

      {status === "success" && (
        <>
          <CheckCircle2 className="h-10 w-10 mb-6 text-primary" />
          <h1 className="text-2xl font-semibold">Store connected successfully!</h1>
          <Link
            to="/dashboard"
            className="mt-6 inline-flex items-center justify-center rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium hover:opacity-90 transition"
          >
            Return to Dashboard
          </Link>
        </>
      )}

      {status === "error" && (
        <>
          <AlertCircle className="h-10 w-10 mb-6 text-destructive" />
          <h1 className="text-2xl font-semibold">Connection failed</h1>
          <pre className="mt-4 max-w-lg whitespace-pre-wrap break-words rounded-md border border-border bg-muted p-4 text-left text-sm text-muted-foreground">
            {error}
          </pre>
          <Link
            to="/dashboard"
            className="mt-6 inline-flex items-center justify-center rounded-md border border-border px-4 py-2 text-sm font-medium hover:bg-muted transition"
          >
            Return to Dashboard
          </Link>
        </>
      )}
    </div>
  );
}
