"use client";

import { useRouter } from "next/navigation";
import { useCallback, useEffect } from "react";
import { useSWRConfig } from "swr";

import { getWalletBalance } from "@/api/wallet";
import { TransferOutPage } from "@/features/wallet/wallet-transfer-forms";
import { Skeleton } from "@/components/ui/skeleton";
import { useActivePlayerCurrency } from "@/hooks/use-active-player-currency";
import { useApiQuery } from "@/hooks/use-api-query";
import { PLAYER_CURRENCY_CHANGE_EVENT } from "@/lib/player-currency-preference";

const BALANCE_KEY = (currency: string) => ["wallet/balance", currency];

/** 独立路由 `/wallet/transfer-out` */
export function TransferOutScreen() {
  const router = useRouter();
  const { activeCurrency: currency } = useActivePlayerCurrency();
  const { mutate } = useSWRConfig();

  const { data: balance, isLoading: loading } = useApiQuery(
    BALANCE_KEY(currency),
    () => getWalletBalance({ currency }),
  );

  // 币种切换时 SWR key 自动变化，此处仅处理全局事件触发的刷新
  useEffect(() => {
    const onRefresh = () => void mutate(BALANCE_KEY(currency));
    window.addEventListener(PLAYER_CURRENCY_CHANGE_EVENT, onRefresh);
    return () => window.removeEventListener(PLAYER_CURRENCY_CHANGE_EVENT, onRefresh);
  }, [mutate, currency]);

  const onSuccess = useCallback(async () => {
    await mutate(BALANCE_KEY(currency));
    router.push("/wallet");
  }, [mutate, currency, router]);

  if (loading && !balance) {
    return (
      <div className="space-y-3">
        <Skeleton className="h-8 w-40" />
        <Skeleton className="h-48 w-full rounded-xl" />
      </div>
    );
  }

  return (
    <TransferOutPage
      currency={currency}
      availableMinor={Number(balance?.available_balance ?? 0)}
      onSuccess={onSuccess}
    />
  );
}
