import { type ReactNode } from "react";
import Image from "next/image";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { SuccessApiResponse } from "../../../types/api-response";
import { ProfileResponse } from "../../../hooks/features/profile/useProfileFetch";
import StoreHydrator from "../../../components/StoreHydrator";

type GetProfileResponse = Promise<
  SuccessApiResponse<ProfileResponse & { balance: number }>
>;

async function getProfile(): GetProfileResponse {
  const cookieStore = await cookies();
  const token = cookieStore.get("accessToken")?.value;
  const refreshToken = cookieStore.get("refreshToken")?.value;

  const res = await fetch(`${process.env.APP_URL}/profile`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: "no-store",
  });

  if (!res.ok) {
    redirect("/");
  }

  if (res.status === 401) {
    // remove cookies as well
    // redirect("/");

    const refreshRes = await fetch(
      `${process.env.APP_URL}/auth/refresh-token`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          refreshToken,
        }),
      },
    );

    if (!refreshRes.ok) {
      return null;
    }

    const refreshData = await refreshRes.json();

    const newAccessToken = refreshData.data.accessToken;
    const newRefreshToken = refreshData.data.refreshToken;

    const res = await fetch(`/api/auth/login`, {
      method: "POST",
      body: JSON.stringify({
        accessToken: newAccessToken,
        refreshToken: newRefreshToken,
      }),
    });
  }

  const apiKeyRes = await fetch(`${process.env.APP_URL}/api-keys/current`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: "no-store",
  });

  const apiKeys = await apiKeyRes.json();

  const obj = await res.json();

  obj.data.apiKey = apiKeys?.data?.apiKey;

  const walletResponse = await fetch(`${process.env.APP_URL}/wallet`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: "no-store",
  });

  const wallet = await walletResponse.json();

  obj.data.balance = wallet.data.balance;

  return obj as GetProfileResponse;
}

export default async function UserLayout({
  children,
}: {
  children: ReactNode;
}) {
  const profile = await getProfile();

  return (
    <div className="relative overflow-hidden">
      <div className="absolute inset-0 -z-10">
        <Image
          src="/images/dashboard-bg.svg"
          alt="Hero Background"
          fill
          priority
          className="object-cover"
        />
      </div>
      <StoreHydrator profile={profile.data} />
      <main className="pt-32 pb-8 sm:pt-36 sm:pb-8 xl:pt-40 md:pb-section 2xl:pt-48 xl:px-4">
        {/* <ClientWrapper>{children}</ClientWrapper> */}
        {children}
      </main>
    </div>
  );
}
