import { getMe } from "@/modules/authModule/signin/actions/authActions";
import { redirect } from "next/navigation";
import { getServerAuthData } from "@/lib/server-auth";
import BackButton from "@/components/ui/buttons-group/ButtonBack";
import { WithdrawalForm } from "./components/WithdrawalForm";
import { getLatestRefundPolicy } from "@/sanity/cms";
import { getSanityOrgCode } from "@/sanity/tenantOrg.server";

const JURISDICTION_LIST = ['ID', 'SG', 'MY', 'GLOBAL', 'VN']
const LOCALE_LIST = ['en-US', 'id-ID']

export const WithdrawalModule: React.FC = async () => {
  let user = null;
  let wallet = { balance: 0, currency: "IDR" };

  // Get auth data with automatic refresh handling
  // This will handle token refresh if access_token is missing but refresh_token exists
  const authData = await getServerAuthData();
  if (!authData) {
    return redirect("/signin");
  }

  try {
    // Fetch user data
    const result = await getMe();
    if (result.success && result.user) {
      user = result.user;
      wallet = result.user.wallet || wallet;
    } else {
      console.error("Authentication failed:", result.error);
      return redirect("/signin");
    }
  } catch (err: any) {
    console.error("Server Error: Failed to authenticate user:", err);
    return redirect("/signin");
  }

  // Fetch Refund Policy from Sanity to use as TNC
  let refundPolicy = null;
  try {
    const orgCode = await getSanityOrgCode();
    if (orgCode) {
      const jurisdiction = JURISDICTION_LIST[0];
      const locale = LOCALE_LIST[0];
      refundPolicy = await getLatestRefundPolicy(orgCode, jurisdiction, locale);
    }
  } catch (err: any) {
    console.warn("Failed to fetch refund policy from Sanity:", err);
    // Continue without refund policy - component will fallback to default
  }

  return (
    <div className="flex flex-col min-h-screen">
      <div className="mx-auto mt-4 w-full max-w-2xl lg:max-w-4xl px-4 space-y-6">
        <BackButton />
        <WithdrawalForm
          currentBalance={wallet.balance}
          currency={wallet.currency}
          initialProfile={user}
          withdrawalTnC={refundPolicy}
        />
      </div>
    </div>
  );
};
