import { useEffect } from "react";
import { Loader2 } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { apiRequest } from "@/lib/queryClient";
import PageEnter from "@/components/ui/page-enter";
import {
  buildZerodhaBackendCallbackUrl,
  parseZerodhaCallbackParams,
  type ZerodhaCallbackParams,
} from "./zerodhaCallbackUtils";

const CALLBACK_STORAGE_KEY = "zerodha:callback";
const RETURN_PATH = "/portfolio";

const parseParams = (): ZerodhaCallbackParams => parseZerodhaCallbackParams(window.location.search);

export default function ZerodhaCallback() {
  useEffect(() => {
    const params = parseParams();
    const finalize = (status: "success" | "error", message?: string) => {
      try {
        localStorage.setItem(
          CALLBACK_STORAGE_KEY,
          JSON.stringify({ status, message: message || "", ts: Date.now() }),
        );
      } catch {}
      window.close();
      window.location.replace(RETURN_PATH);
    };

    if (params.error || (params.status && params.status !== "success")) {
      finalize("error", params.errorDescription || "Zerodha login was not successful.");
      return;
    }

    if (!params.requestToken) {
      finalize("error", "Missing request_token in the redirect URL.");
      return;
    }

    if (!params.state) {
      finalize("error", "Missing callback state in the redirect URL.");
      return;
    }

    const url = buildZerodhaBackendCallbackUrl(params);
    apiRequest("GET", url)
      .then(() => finalize("success"))
      .catch((err: any) => finalize("error", err?.message || "Unable to complete the login."));
  }, []);

  return (
    <div className="min-h-screen w-full flex items-center justify-center bg-gray-50 px-4">
      <PageEnter>
        <Card className="w-full max-w-md">
          <CardContent className="pt-6 space-y-3">
            <div className="flex items-center gap-2">
              <Loader2 className="h-8 w-8 text-muted-foreground animate-spin" />
              <h1 className="text-2xl font-bold text-gray-900">Completing Zerodha login</h1>
            </div>
            <p className="text-sm text-gray-600">
              You can close this tab if it does not close automatically.
            </p>
          </CardContent>
        </Card>
      </PageEnter>
    </div>
  );
}
