"use client";

import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";

import { customerGuestImpersonateUrl, customerUrl, defaultCustomerTenant } from "@/lib/tenant";
import { applyUiPrefsLocally } from "@/lib/preferences/apply-ui-prefs-locally";
import { parseUiPrefs } from "@/lib/preferences/ui-prefs";
import { syncPreferenceCookies } from "@/lib/preferences/sync-preference-cookies";

type CustomerImpersonateScreenProps = {
  tenant: string;
};

/** Only allow same-origin relative portal paths as post-login targets (avoids open redirects). */
function sanitizeNextTarget(next: string | null): string | null {
  if (!next || !next.startsWith("/") || next.startsWith("//")) {
    return null;
  }
  return next;
}

/** Shared impersonation bootstrap (host-style `/customer/impersonate` or path-style). */
export function CustomerImpersonateScreen({ tenant }: CustomerImpersonateScreenProps) {
  const searchParams = useSearchParams();
  const [error, setError] = useState<string | null>(null);
  const startedRef = useRef(false);

  useEffect(() => {
    if (startedRef.current) {
      return;
    }

    const customerUid = searchParams.get("customer_uid") ?? searchParams.get("impersonate") ?? "";
    const customerId = searchParams.get("customer_id");
    const impersonationToken = searchParams.get("impersonation_token") ?? "";
    const launchToken = searchParams.get("launch_token") ?? "";

    if (!customerUid && !customerId) {
      setError("Missing customer identifier for impersonation.");
      return;
    }

    startedRef.current = true;

    void (async () => {
      try {
        const response = await fetch(customerGuestImpersonateUrl(tenant), {
          method: "POST",
          credentials: "same-origin",
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            customer_uid: customerUid || undefined,
            customer_id: customerId ? Number(customerId) : undefined,
            impersonation_token: impersonationToken || undefined,
            launch_token: launchToken || undefined,
          }),
        });

        const data = (await response.json().catch(() => null)) as
          | {
              status?: string;
              message?: string;
              tenant?: { subdomain?: string };
              impersonated?: boolean;
              impersonation_type?: string | null;
              uiPrefs?: unknown;
            }
          | null;
        if (!response.ok || data?.status !== "success") {
          setError(
            data?.message ??
              "Impersonation failed. Open a fresh link from Temp Data — these tokens are single-use.",
          );
          return;
        }

        // Corporate impersonation adopts the target user's Appearance.
        // Admin impersonation keeps the admin's current theme cookies.
        const isAdminImpersonation =
          Boolean(data.impersonated) && data.impersonation_type === "admin";
        if (!isAdminImpersonation && data.uiPrefs != null) {
          const prefs = parseUiPrefs(data.uiPrefs);
          applyUiPrefsLocally(prefs);
          void syncPreferenceCookies(prefs);
        }

        const resolvedTenant = data.tenant?.subdomain?.trim() || tenant;
        const nextTarget = sanitizeNextTarget(searchParams.get("next"));
        // Relative path — already on the correct tenant host; avoid inventing *.localhost.
        window.location.assign(
          customerUrl(resolvedTenant, nextTarget ?? "/dashboard", window.location.hostname),
        );
      } catch {
        setError("Could not reach the impersonation service. Check your connection and try again.");
        startedRef.current = false;
      }
    })();
  }, [searchParams, tenant]);

  return (
    <main className="flex min-h-screen items-center justify-center p-6">
      <div className="text-center">
        <p className="text-lg font-medium">{error ? "Impersonation failed" : "Signing in as customer..."}</p>
        {error ? <p className="mt-2 text-sm text-muted-foreground">{error}</p> : null}
        {!error ? (
          <p className="mt-2 text-sm text-muted-foreground">
            Continue to {customerUrl(tenant || defaultCustomerTenant(), "/dashboard")}
          </p>
        ) : null}
      </div>
    </main>
  );
}
