"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useSetAtom } from "jotai";
import { useParams, useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { createPurchaseOffer } from "@/actions/purchase-offers";
import { payWithGateway, payWithWallet } from "@/actions/payment";
import {
  buildReturnPathForGatewayRequest,
  persistGatewayMetaFromGatewayResponse,
} from "@/lib/payment-return";
import { useSession } from "@/auth/session-provider";
import { useAppToast } from "@/app/[lang]/providers";
import { useWalletBalances } from "@/lib/clientQueries";
import { useApplePayVisible } from "@/lib/platform";
import { loginModalAtom } from "@/components/state/loginAtom";
import PaymentGatewayModal from "@/components/payment/PaymentGatewayModal";
import TopUpModal from "@/components/sections/wallet/TopUpModal";
import RoomItemsPanel from "@/components/annaulMazad/live-rooms-table/RoomItemsPanel";
import RoomsTableCard from "@/components/annaulMazad/live-rooms-table/RoomsTableCard";
import {
  ConfirmActionModal,
  OfferModal,
  PaddlePurchaseModal,
} from "@/components/annaulMazad/live-rooms-table/LiveRoomsTableModals";
import type {
  GatewayPaymentResult,
  LiveRoom,
  LiveRoomsTableProps,
  RoomDetailsResponse,
  SingleAuctionItem,
  SingleAuctionListResponse,
  WalletPaymentResult,
} from "@/components/annaulMazad/live-rooms-table/types";
import {
  buildInitialRoomsByDay,
  fetchRoomsForDay,
  formatDeadlineLabel,
  getErrorMessage,
  getOfferDeadline,
  parseSingleAuctionsResponse,
  safeFetchJson,
  toFiniteNumber,
} from "@/components/annaulMazad/live-rooms-table/utils";
import { toMoneyNumber } from "@/lib/moneyParse";

export type { LiveClosedSummary } from "@/components/annaulMazad/live-rooms-table/types";

export default function LiveRoomsTable({
  groupId,
  initialRooms,
  maxDays,
  animalType,
  auctionType,
  normalPaddlePrice: groupNormalPaddlePrice,
  premiumPaddlePrice: groupPremiumPaddlePrice,
  onDayChange,
  hideActions = false,
  enablePurchaseOffers = false,
  isResultsPage = false,
  closedSummariesByRoomId = {},
  activeAuctionGroupId = null,
  activeRoomLivePrice = null,
  hidePriceAndWinner = false,
}: LiveRoomsTableProps) {
  const router = useRouter();
  const params = useParams<{ lang?: string }>();
  const locale = useLocale();
  const isRtl = (locale || "").toLowerCase().startsWith("ar");
  const t = useTranslations("ANNUAL_AUCTION_RESULTS");
  const tStatus = useTranslations("INNER_AUCTIONS_TABLE");
  const tAuction = useTranslations("AUCTION");
  const tToast = useTranslations("TOAST");
  const toast = useAppToast();
  const session = useSession();

  const apiBase =
    (typeof process !== "undefined" && process.env.NEXT_PUBLIC_BASE_URL) ||
    "https://dev-endpoint.ataya.sa/api";
  const lang = (params?.lang as string) || locale || "ar";

  const days = useMemo(() => {
    const safeMaxDays =
      Number.isFinite(maxDays) && maxDays > 0 ? Math.max(1, maxDays) : 0;

    return safeMaxDays > 0
      ? Array.from({ length: safeMaxDays }, (_, index) => index + 1)
      : [];
  }, [maxDays]);

  const initialRoomsByDay = useMemo(
    () => buildInitialRoomsByDay(initialRooms, days),
    [days, initialRooms],
  );

  const [activeDay, setActiveDay] = useState<number>(1);
  const [selectedRoomId, setSelectedRoomId] = useState<string | null>(null);
  const [loadingRoom, setLoadingRoom] = useState(false);
  const [roomItems, setRoomItems] = useState<SingleAuctionItem[]>([]);
  const [rooms, setRooms] = useState<LiveRoom[]>(
    initialRoomsByDay.get(1) ?? [],
  );
  const [loadingRooms, setLoadingRooms] = useState(false);
  const roomsCache = useRef<Map<number, LiveRoom[]>>(initialRoomsByDay);
  const activeDayRef = useRef(activeDay);

  const [actionItem, setActionItem] = useState<SingleAuctionItem | null>(null);
  const [withdrawModalOpen, setWithdrawModalOpen] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);

  const [offerModalOpen, setOfferModalOpen] = useState(false);
  const [selectedOfferRoom, setSelectedOfferRoom] = useState<LiveRoom | null>(
    null,
  );
  const [offerAmount, setOfferAmount] = useState("");
  const [sendingOffer, setSendingOffer] = useState(false);

  const [paddleModalOpen, setPaddleModalOpen] = useState(false);
  const [selectedPaddleRoom, setSelectedPaddleRoom] = useState<LiveRoom | null>(
    null,
  );
  const applePayVisible = useApplePayVisible();
  const [paddlePaymentMethod, setPaddlePaymentMethod] = useState<
    "wallet" | "gateway" | "apple_pay"
  >("gateway");
  const [buyingPaddle, setBuyingPaddle] = useState(false);
  const [paddleType, setPaddleType] = useState<"normal" | "premium">("normal");
  const [showTopUpModal, setShowTopUpModal] = useState(false);
  const [gatewayUrl, setGatewayUrl] = useState<string | null>(null);

  const setLoginModal = useSetAtom(loginModalAtom);
  const { data: walletBalances } = useWalletBalances();
  const wallet = toMoneyNumber(walletBalances?.available_balance, 0);
  const PADDLE_PRICE = 100;

  useEffect(() => {
    activeDayRef.current = activeDay;
  }, [activeDay]);

  useEffect(() => {
    roomsCache.current = new Map(initialRoomsByDay);

    if (activeDayRef.current === 1) {
      setRooms(initialRoomsByDay.get(1) ?? []);
    }
  }, [initialRoomsByDay]);

  useEffect(() => {
    console.log("[LiveRoomsTable] initial rooms", {
      groupId,
      animalType,
      maxDays,
      auctionType,
      initialRoomsLength: initialRooms.length,
      initialRoomsByDay: Array.from(initialRoomsByDay.entries()).map(
        ([day, list]) => ({
          day,
          length: list.length,
          ids: list.map((room) => room.id),
        }),
      ),
    });
  }, [
    animalType,
    auctionType,
    groupId,
    initialRooms,
    initialRoomsByDay,
    maxDays,
  ]);

  useEffect(() => {
    setSelectedRoomId(null);
    setRoomItems([]);
  }, [groupId]);

  const daysKey = useMemo(() => days.join(","), [days]);

  const minOfferPrice = useMemo(() => {
    if (!selectedOfferRoom) return 0;

    const st = String(selectedOfferRoom.status || "").toLowerCase();
    if (st === "unsold") {
      return toFiniteNumber(
        selectedOfferRoom.info_final_bid?.lowest_offer_value ?? 0,
      );
    }

    return toFiniteNumber(
      selectedOfferRoom.winning_bid?.amount ??
        selectedOfferRoom.market_entry_price ??
        0,
    );
  }, [selectedOfferRoom]);

  const offerDeadlineLabel = useMemo(
    () => formatDeadlineLabel(getOfferDeadline(selectedOfferRoom)),
    [selectedOfferRoom],
  );

  const getLocalizedText = (text: string | null | undefined) => {
    if (!text) return text;

    try {
      const parsed = JSON.parse(text) as Record<string, unknown>;
      const localized = parsed[lang] ?? parsed[locale] ?? parsed.en;
      return typeof localized === "string" && localized.trim()
        ? localized
        : text;
    } catch {
      return text;
    }
  };

  const resolveRoomTitle = (room: LiveRoom) => {
    const roomOrder = room.day_order ?? 1;

    // Horses: headline must be the animal name from single_auctions data, not auction_group.name.
    if (animalType === "horse") {
      const fromAnimal =
        getLocalizedText(room.animal?.name) ||
        getLocalizedText(
          (room as { horse?: { name?: string | null } | null }).horse?.name,
        );
      const trimmed = (fromAnimal || "").trim();
      if (trimmed) return trimmed;
    }

    return (
      getLocalizedText(room.name) ||
      (animalType === "horse"
        ? tStatus("rooms_table.title_horse_fallback", {
            id: room.first_single_auction_id || roomOrder,
          })
        : tStatus("rooms_table.title_room_fallback", {
            number: roomOrder,
          }))
    );
  };

  const statusClass = (state: string | null | undefined) => {
    const value = (state || "").toLowerCase();
    const classes: Record<string, string> = {
      active: "bg-emerald-500 text-white",
      running: "bg-emerald-500 text-white",
      live: "bg-emerald-500 text-white",
      accepted: "bg-emerald-500 text-white",
      pending: "bg-amber-500 text-white",
      upcoming: "bg-amber-500 text-white",
      finished: "bg-slate-500 text-white",
      closed: "bg-slate-500 text-white",
      sold: "bg-emerald-700 text-white",
      "تم البيع": "bg-emerald-700 text-white",
      مباع: "bg-emerald-700 text-white",
      unsold: "bg-orange-500 text-white",
      "غير مباع": "bg-orange-500 text-white",
      "لم يتم البيع": "bg-orange-500 text-white",
      withdrawn: "bg-sky-600 text-white",
      مسحوب: "bg-sky-600 text-white",
      منسحب: "bg-sky-600 text-white",
      pulled: "bg-sky-600 text-white",
      skipped: "bg-violet-600 text-white",
      "تم التخطي": "bg-violet-600 text-white",
    };

    return classes[value] || "bg-slate-200 text-slate-800";
  };

  const resolveBackendStatus = (raw: string | null | undefined) => {
    const key = (raw || "").trim().toLowerCase();

    if (!key) return { statusKey: "", statusLabel: "" };
    if (key === "accepted") {
      return { statusKey: "accepted", statusLabel: tStatus("status.accepted") };
    }
    if (key === "pending" || key === "pendind") {
      return { statusKey: "pending", statusLabel: tStatus("status.pending") };
    }
    if (key === "live") {
      return { statusKey: "live", statusLabel: tStatus("status.live") };
    }
    if (key === "sold" || key === "مباع" || key === "تم البيع") {
      return { statusKey: "sold", statusLabel: tStatus("status.sold") };
    }
    if (key === "skipped" || key === "تم التخطي") {
      return { statusKey: "skipped", statusLabel: tStatus("status.skipped") };
    }
    if (key === "unsold" || key === "غير مباع" || key === "لم يتم البيع") {
      return { statusKey: "unsold", statusLabel: tStatus("status.unsold") };
    }
    if (key === "withdrawn" || key === "مسحوب" || key === "منسحب") {
      return {
        statusKey: "withdrawn",
        statusLabel: tStatus("status.withdrawn"),
      };
    }
    if (key === "pulled") {
      return {
        statusKey: "pulled",
        statusLabel: tStatus("status.withdrawn"),
      };
    }

    if (key === "closed") {
      return { statusKey: "closed", statusLabel: tStatus("status.closed") };
    }

    return { statusKey: key, statusLabel: raw || key };
  };

  useEffect(() => {
    if (days.length > 0 && !days.includes(activeDay)) {
      setActiveDay(days[0]);
    }
  }, [activeDay, days]);

  useEffect(() => {
    const cachedRooms = roomsCache.current.get(activeDay);
    if (cachedRooms) {
      setRooms(cachedRooms);
    }
  }, [activeDay]);

  useEffect(() => {
    let cancelled = false;

    const run = async () => {
      setLoadingRooms(true);

      try {
        const nextCache = new Map<number, LiveRoom[]>(initialRoomsByDay);

        if (days.length > 0) {
          const results = await Promise.all(
            days.map(async (day) => ({
              day,
              rooms: await fetchRoomsForDay({
                apiBase,
                groupId,
                token: session?.access_token,
                day,
              }),
            })),
          );

          if (cancelled) return;

          results.forEach(({ day, rooms: dayRooms }) => {
            console.log("[LiveRoomsTable] fetched day rooms", {
              groupId,
              animalType,
              day,
              length: dayRooms.length,
              ids: dayRooms.map((room) => room.id),
            });

            if (
              dayRooms.length > 0 ||
              !(initialRoomsByDay.get(day)?.length ?? 0)
            ) {
              nextCache.set(day, dayRooms);
              return;
            }

            console.warn(
              "[LiveRoomsTable] keeping initial rooms for empty day fetch",
              {
                groupId,
                animalType,
                day,
                initialLength: initialRoomsByDay.get(day)?.length ?? 0,
              },
            );
          });
        } else {
          const allRooms = await fetchRoomsForDay({
            apiBase,
            groupId,
            token: session?.access_token,
          });

          if (cancelled) return;

          console.log("[LiveRoomsTable] fetched all rooms", {
            groupId,
            animalType,
            length: allRooms.length,
            ids: allRooms.map((room) => room.id),
          });

          if (allRooms.length > 0 || initialRooms.length === 0) {
            nextCache.set(1, allRooms);
          } else {
            console.warn(
              "[LiveRoomsTable] keeping initial rooms after empty fetch",
              {
                groupId,
                animalType,
                initialLength: initialRooms.length,
              },
            );
          }
        }

        roomsCache.current = nextCache;
        setRooms(
          nextCache.get(activeDayRef.current) ??
            nextCache.get(1) ??
            initialRoomsByDay.get(1) ??
            initialRooms,
        );
      } catch (error) {
        console.error("Error fetching auction groups:", error);

        try {
          const fallbackRooms = await fetchRoomsForDay({
            apiBase,
            groupId,
            token: session?.access_token,
            day: activeDayRef.current,
          });

          if (cancelled) return;

          const nextCache = new Map(roomsCache.current);
          if (
            fallbackRooms.length > 0 ||
            !(initialRoomsByDay.get(activeDayRef.current)?.length ?? 0)
          ) {
            nextCache.set(activeDayRef.current, fallbackRooms);
          } else {
            console.warn(
              "[LiveRoomsTable] fallback fetch empty, keeping initial rooms",
              {
                groupId,
                animalType,
                day: activeDayRef.current,
                initialLength:
                  initialRoomsByDay.get(activeDayRef.current)?.length ?? 0,
              },
            );
          }
          roomsCache.current = nextCache;
          setRooms(
            nextCache.get(activeDayRef.current) ??
              initialRoomsByDay.get(activeDayRef.current) ??
              initialRoomsByDay.get(1) ??
              [],
          );
        } catch (fallbackError) {
          console.error(
            "Error fetching fallback auction groups:",
            fallbackError,
          );

          if (!cancelled) {
            setRooms(
              roomsCache.current.get(activeDayRef.current) ??
                initialRoomsByDay.get(activeDayRef.current) ??
                initialRoomsByDay.get(1) ??
                initialRooms,
            );
          }
        }
      } finally {
        if (!cancelled) {
          setLoadingRooms(false);
        }
      }
    };

    void run();

    return () => {
      cancelled = true;
    };
  }, [
    apiBase,
    animalType,
    days,
    daysKey,
    groupId,
    initialRooms,
    initialRoomsByDay,
    session?.access_token,
  ]);

  const refreshAuctionRoomsSilently = useCallback(async () => {
    const nextCache = new Map<number, LiveRoom[]>(roomsCache.current);
    try {
      if (days.length > 0) {
        const results = await Promise.all(
          days.map(async (day) => ({
            day,
            rooms: await fetchRoomsForDay({
              apiBase,
              groupId,
              token: session?.access_token,
              day,
            }),
          })),
        );
        for (const { day, rooms: dayRooms } of results) {
          if (
            dayRooms.length > 0 ||
            !(initialRoomsByDay.get(day)?.length ?? 0)
          ) {
            nextCache.set(day, dayRooms);
          }
        }
      } else {
        const allRooms = await fetchRoomsForDay({
          apiBase,
          groupId,
          token: session?.access_token,
        });
        if (allRooms.length > 0 || initialRooms.length === 0) {
          nextCache.set(1, allRooms);
        }
      }
      roomsCache.current = nextCache;
      setRooms(
        nextCache.get(activeDayRef.current) ??
          nextCache.get(1) ??
          initialRoomsByDay.get(1) ??
          initialRooms,
      );
    } catch (e) {
      console.error("[LiveRoomsTable] refresh rooms after offer failed:", e);
    }
  }, [
    apiBase,
    days,
    groupId,
    initialRooms,
    initialRoomsByDay,
    session?.access_token,
  ]);

  const loadRoomItems = async (
    roomId: string,
  ): Promise<SingleAuctionItem[]> => {
    const requestOptions: RequestInit = {
      method: "GET",
      headers: {
        Accept: "application/json",
        ...(session?.access_token
          ? { Authorization: `Bearer ${session.access_token}` }
          : undefined),
      },
      credentials: "omit",
      cache: "no-store",
    };

    const apiRouteResponse = await safeFetchJson<SingleAuctionListResponse>(
      `/api/group-single-auctions?groupId=${encodeURIComponent(groupId)}&auction_group_id=${encodeURIComponent(roomId)}`,
      {
        credentials: "include",
        cache: "no-store",
      },
    );

    if (apiRouteResponse.ok) {
      const apiRouteItems = parseSingleAuctionsResponse(apiRouteResponse.json);
      if (apiRouteItems.length > 0) return apiRouteItems;
    }

    const directBackendResponse =
      await safeFetchJson<SingleAuctionListResponse>(
        `${apiBase}/user/group-auctions/${groupId}/single-auctions?auction_group_id=${encodeURIComponent(roomId)}`,
        requestOptions,
      );

    const directBackendItems = parseSingleAuctionsResponse(
      directBackendResponse.json,
    );
    if (directBackendItems.length > 0) return directBackendItems;

    const pathBasedResponse = await safeFetchJson<SingleAuctionListResponse>(
      `${apiBase}/user/group-auctions/${groupId}/auction-groups/${encodeURIComponent(roomId)}/single-auctions`,
      requestOptions,
    );

    const pathBasedItems = parseSingleAuctionsResponse(pathBasedResponse.json);
    if (pathBasedItems.length > 0) return pathBasedItems;

    const detailsResponse = await safeFetchJson<RoomDetailsResponse>(
      `${apiBase}/user/group-auctions/${groupId}/auction-groups/${encodeURIComponent(roomId)}`,
      requestOptions,
    );

    if (!detailsResponse.ok) return [];

    return parseSingleAuctionsResponse({
      data:
        detailsResponse.json.data?.single_auctions ??
        detailsResponse.json.data?.items ??
        [],
    });
  };

  const fetchRoomItems = async (roomId: string) => {
    setSelectedRoomId(roomId);
    setLoadingRoom(true);
    setRoomItems([]);

    try {
      const items = await loadRoomItems(roomId);
      setRoomItems(items);
    } catch {
      setRoomItems([]);
    } finally {
      setLoadingRoom(false);
    }
  };

  const handleEditItem = (item: SingleAuctionItem) => {
    router.push(
      `/${lang}/dashboard/my-group-auctions/${groupId}/edit/${item.id}`,
    );
  };

  const handleViewItem = (item: SingleAuctionItem) => {
    window.open(
      `/${lang}/annual-item/${String(item.id ?? "")}`,
      "_blank",
      "noopener,noreferrer",
    );
  };

  const handleRoomClick = (room: LiveRoom) => {
    console.log(room, "room wehn click ");
    if (animalType === "camel") {
      router.push(`/${lang}/annual-auctions/${groupId}/group/${room.id}`);
      return;
    }
    if (animalType === "horse") {
      if (isResultsPage) {
        router.push(`/${lang}/annual/${room.first_single_auction_id}`);
        return;
      }
      router.push(`/${lang}/annual/${room.first_single_auction_id}`);
      return;
    }
    void fetchRoomItems(room.id);
  };

  const closeWithdrawModal = () => {
    setWithdrawModalOpen(false);
    setActionItem(null);
  };

  const closeDeleteModal = () => {
    setDeleteModalOpen(false);
    setActionItem(null);
  };

  const closeOfferModal = () => {
    setOfferModalOpen(false);
    setSelectedOfferRoom(null);
    setOfferAmount("");
  };

  const closePaddleModal = () => {
    setPaddleModalOpen(false);
    setSelectedPaddleRoom(null);
    setPaddleType("normal");
  };

  const requireLogin = () => {
    toast.warning(tToast("login_required"));
  };

  const handleBuyPaddleRequest = (room: LiveRoom) => {
    if (!session) {
      requireLogin();
      return;
    }

    setSelectedPaddleRoom(room);
    setPaddleModalOpen(true);
  };

  const handleSendOfferRequest = (room: LiveRoom) => {
    if (!session) {
      requireLogin();
      return;
    }

    setSelectedOfferRoom(room);
    setOfferAmount("");
    setOfferModalOpen(true);
  };

  const handleWithdrawItem = async () => {
    if (!actionItem) return;

    setActionLoading(true);

    try {
      const response = await fetch(
        `${apiBase}/user/dashboard/single-auctions/${actionItem.id}/withdraw`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${session?.access_token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ _method: "put" }),
        },
      );

      if (response.ok && selectedRoomId) {
        await fetchRoomItems(selectedRoomId);
      }
    } catch (error) {
      console.error("Withdraw error:", error);
    } finally {
      setActionLoading(false);
      closeWithdrawModal();
    }
  };

  const handleDeleteItem = async () => {
    if (!actionItem) return;

    setActionLoading(true);

    try {
      const response = await fetch(
        `${apiBase}/user/dashboard/single-auctions/${actionItem.id}`,
        {
          method: "DELETE",
          headers: {
            Authorization: `Bearer ${session?.access_token}`,
            Accept: "application/json",
          },
        },
      );

      if (response.ok && selectedRoomId) {
        await fetchRoomItems(selectedRoomId);
      }
    } catch (error) {
      console.error("Delete error:", error);
    } finally {
      setActionLoading(false);
      closeDeleteModal();
    }
  };

  const handleSendOffer = async () => {
    if (!selectedOfferRoom) return;

    const amount = toMoneyNumber(offerAmount, 0);
    if (!Number.isFinite(amount) || amount <= 0) {
      toast.error(tToast("enter_valid_offer_amount"));
      return;
    }

    if (minOfferPrice > 0 && amount <= minOfferPrice) {
      toast.error(
        tToast("offer_must_exceed_min", {
          min: minOfferPrice.toLocaleString(),
        }),
      );
      return;
    }

    setSendingOffer(true);

    const submittedRoomId = selectedOfferRoom.id;

    try {
      const result = await createPurchaseOffer({
        auction_type: "group",
        auction_id: submittedRoomId,
        full_amount: amount,
      });

      if (result.success) {
        toast.success(
          result.message || tToast("offer_sent_success"),
        );
        await refreshAuctionRoomsSilently();
        closeOfferModal();
      } else {
        toast.error(
          result.message || tToast("offer_send_failed"),
        );
      }
    } catch (error) {
      console.error("Send offer error:", error);
      toast.error(
        getErrorMessage(error) || tToast("offer_send_failed"),
      );
    } finally {
      setSendingOffer(false);
    }
  };

  const handlePurchasePaddle = async (typeOverride?: "normal" | "premium") => {
    if (!selectedPaddleRoom || !session) return;

    const selectedType = typeOverride || paddleType;
    const resolvedAuctionType = isResultsPage ? "group" : "annual";

    setBuyingPaddle(true);

    try {
      if (
        paddlePaymentMethod === "gateway" ||
        paddlePaymentMethod === "apple_pay"
      ) {
        const priceForPurchase =
          selectedType === "premium" ? premiumPaddlePrice : normalPaddlePrice;
        const returnPath = buildReturnPathForGatewayRequest() ?? "/";
        const result: GatewayPaymentResult = await payWithGateway({
          payment_purpose: "pay_paddle_fee",
          auction_id: String(selectedPaddleRoom.id),
          auction_type: resolvedAuctionType,
          ...(isResultsPage
            ? { amount: priceForPurchase }
            : { paddle_type: selectedType }),
          payment_method:
            paddlePaymentMethod === "apple_pay"
              ? "apple_pay"
              : "online_payment",
          return_path: returnPath,
        });
        const paymentUrl =
          result.data?.payment_url || result.data?.redirect_url || null;

        if (result.success && paymentUrl) {
          persistGatewayMetaFromGatewayResponse(
            result.data as Record<string, unknown>,
            returnPath,
          );
          toast.success(tToast("redirecting_gateway"));
          setGatewayUrl(paymentUrl);
        } else {
          toast.error(
            result.message || tToast("gateway_open_failed"),
          );
        }
      } else {
        const canAffordSelectedPaddle =
          selectedType === "premium"
            ? canAffordPremiumPaddle
            : canAffordNormalPaddle;

        if (!canAffordSelectedPaddle) {
          toast.error(tToast("insufficient_wallet_paddle"));
          return;
        }

        const result: WalletPaymentResult = await payWithWallet({
          payment_purpose: "pay_paddle_fee",
          auction_id: String(selectedPaddleRoom.id),
          auction_type: resolvedAuctionType,
          ...(isResultsPage ? {} : { paddle_type: selectedType }),
        });

        if (result.success) {
          toast.success(
            result.message || tToast("paddle_purchase_success"),
          );
          const roomToOffer = selectedPaddleRoom;
          closePaddleModal();
          router.refresh();
          if (enablePurchaseOffers && roomToOffer?.can_send_offer) {
            setSelectedOfferRoom(roomToOffer);
            setOfferAmount("");
            setOfferModalOpen(true);
          }
        } else {
          toast.error(
            result.message || tToast("paddle_purchase_failed"),
          );
        }
      }
    } catch (error) {
      console.error("Paddle purchase error:", error);
      toast.error(
        getErrorMessage(error) || tToast("paddle_purchase_failed"),
      );
    } finally {
      setBuyingPaddle(false);
    }
  };

  const currentSelectedRoom = useMemo(() => {
    if (!selectedRoomId) return null;

    const cachedRooms = Array.from(roomsCache.current.values()).flat();

    return (
      rooms.find((room) => room.id === selectedRoomId) ||
      cachedRooms.find((room) => room.id === selectedRoomId) ||
      null
    );
  }, [rooms, selectedRoomId]);

  const selectedPaddleRoomName = selectedPaddleRoom
    ? resolveRoomTitle(selectedPaddleRoom)
    : "—";
  const selectedPaddleRoomNumber =
    selectedPaddleRoom?.day_order != null && selectedPaddleRoom.day_order !== ""
      ? String(selectedPaddleRoom.day_order)
      : "—";
  const selectedPaymentMethodLabel =
    paddlePaymentMethod === "wallet"
      ? isRtl
        ? "المحفظة"
        : "Wallet"
      : paddlePaymentMethod === "apple_pay"
        ? "Apple Pay"
        : isRtl
          ? "دفع إلكتروني"
          : "Online Payment";
  const canBuyPremiumInLive = !isResultsPage;
  const normalPaddlePrice =
    typeof groupNormalPaddlePrice === "number" && groupNormalPaddlePrice > 0
      ? groupNormalPaddlePrice
      : PADDLE_PRICE;
  const premiumPaddlePrice =
    typeof groupPremiumPaddlePrice === "number" && groupPremiumPaddlePrice > 0
      ? groupPremiumPaddlePrice
      : PADDLE_PRICE;
  const canAffordNormalPaddle = wallet >= normalPaddlePrice;
  const canAffordPremiumPaddle = wallet >= premiumPaddlePrice;
  const normalShortfall = Math.max(0, normalPaddlePrice - wallet);
  const premiumShortfall = Math.max(0, premiumPaddlePrice - wallet);
  const hasWalletShortfall =
    paddlePaymentMethod === "wallet" &&
    (normalShortfall > 0 || (canBuyPremiumInLive && premiumShortfall > 0));
  const formatAmount = (value: number) =>
    `${value.toLocaleString()} ${isRtl ? "ر.س" : "SAR"}`;
  const normalWalletStatusMessage = canAffordNormalPaddle
    ? isRtl
      ? "متاح للشراء من المحفظة"
      : "Available via wallet"
    : isRtl
      ? `يحتاج شحن ${formatAmount(normalShortfall)}`
      : `Needs top-up of ${formatAmount(normalShortfall)}`;
  const premiumWalletStatusMessage = canAffordPremiumPaddle
    ? isRtl
      ? "متاح للشراء من المحفظة"
      : "Available via wallet"
    : isRtl
      ? `يحتاج شحن ${formatAmount(premiumShortfall)}`
      : `Needs top-up of ${formatAmount(premiumShortfall)}`;

  /** Top-up matches selected paddle type — not max(normal, premium), which overfilled normal buyers. */
  const walletTopUpDefaultShortfall = hasWalletShortfall
    ? canBuyPremiumInLive && paddleType === "premium"
      ? premiumShortfall
      : normalShortfall
    : 0;

  return (
    <section className="space-y-5">
      <RoomsTableCard
        days={days}
        activeDay={activeDay}
        onDaySelect={(day) => {
          setActiveDay(day);
          onDayChange?.(day);
          setSelectedRoomId(null);
          setRoomItems([]);
        }}
        loadingRooms={loadingRooms}
        rooms={rooms}
        animalType={animalType}
        isRtl={isRtl}
        t={t}
        tStatus={tStatus}
        selectedRoomId={selectedRoomId}
        closedSummariesByRoomId={closedSummariesByRoomId}
        activeAuctionGroupId={activeAuctionGroupId}
        activeRoomLivePrice={activeRoomLivePrice}
        hidePriceAndWinner={hidePriceAndWinner}
        enablePurchaseOffers={enablePurchaseOffers}
        resolveRoomTitle={resolveRoomTitle}
        resolveBackendStatus={resolveBackendStatus}
        statusClass={statusClass}
        onRoomClick={handleRoomClick}
        onBuyPaddle={handleBuyPaddleRequest}
        onSendOffer={handleSendOfferRequest}
        isLoggedIn={!!session}
        onLoginClick={() => setLoginModal(true)}
        isResultsPage={isResultsPage}
      />

      <RoomItemsPanel
        selectedRoomId={selectedRoomId}
        loadingRoom={loadingRoom}
        roomItems={roomItems}
        currentSelectedRoom={currentSelectedRoom}
        hideActions={hideActions}
        isRtl={isRtl}
        tStatus={tStatus}
        resolveRoomTitle={resolveRoomTitle}
        resolveBackendStatus={resolveBackendStatus}
        statusClass={statusClass}
        onViewItem={handleViewItem}
        onEditItem={handleEditItem}
        onWithdrawItem={(item) => {
          setActionItem(item);
          setWithdrawModalOpen(true);
        }}
        onDeleteItem={(item) => {
          setActionItem(item);
          setDeleteModalOpen(true);
        }}
      />

      <ConfirmActionModal
        isOpen={withdrawModalOpen}
        onOpenChange={setWithdrawModalOpen}
        title={isRtl ? "تأكيد السحب" : "Confirm Withdrawal"}
        description={
          isRtl
            ? "هل أنت متأكد من سحب هذه العينة من المزاد؟"
            : "Are you sure you want to withdraw this item from the auction?"
        }
        cancelLabel={isRtl ? "إلغاء" : "Cancel"}
        confirmLabel={isRtl ? "سحب" : "Withdraw"}
        confirmColor="warning"
        isLoading={actionLoading}
        onConfirm={handleWithdrawItem}
        onCancel={closeWithdrawModal}
      />

      <ConfirmActionModal
        isOpen={deleteModalOpen}
        onOpenChange={setDeleteModalOpen}
        title={isRtl ? "تأكيد الحذف" : "Confirm Delete"}
        description={
          isRtl
            ? "هل أنت متأكد من حذف هذه العينة؟ لا يمكن التراجع عن هذا الإجراء."
            : "Are you sure you want to delete this item? This action cannot be undone."
        }
        cancelLabel={isRtl ? "إلغاء" : "Cancel"}
        confirmLabel={isRtl ? "حذف" : "Delete"}
        confirmColor="danger"
        isLoading={actionLoading}
        onConfirm={handleDeleteItem}
        onCancel={closeDeleteModal}
      />

      <OfferModal
        isOpen={offerModalOpen}
        onOpenChange={(open) => {
          setOfferModalOpen(open);
          if (!open) closeOfferModal();
        }}
        isRtl={isRtl}
        title={isRtl ? "تقديم عرض شراء" : "Submit Purchase Offer"}
        description={tAuction("send_offer_description")}
        offerDeadlineLabel={offerDeadlineLabel}
        offerAmountLabel={tAuction("offer_amount_label")}
        offerAmountPlaceholder={tAuction("offer_amount_placeholder")}
        offerAmount={offerAmount}
        onOfferAmountChange={setOfferAmount}
        minOfferPrice={minOfferPrice}
        cancelLabel={isRtl ? "إلغاء" : "Cancel"}
        confirmLabel={tAuction("offer_confirm")}
        sendingOffer={sendingOffer}
        onCancel={closeOfferModal}
        onConfirm={handleSendOffer}
      />

      <PaddlePurchaseModal
        isOpen={paddleModalOpen}
        onOpenChange={(open) => {
          setPaddleModalOpen(open);
          if (!open) closePaddleModal();
        }}
        isRtl={isRtl}
        title={isRtl ? "شراء مضرب" : "Buy Paddle"}
        description={
          isRtl
            ? "اختر طريقة الدفع ونوع المضرب المناسب، ثم أكمل الشراء."
            : "Choose payment method and paddle type, then complete your purchase."
        }
        selectedPaddleRoomName={selectedPaddleRoomName}
        selectedPaddleRoomNumber={selectedPaddleRoomNumber}
        selectedPaymentMethodLabel={selectedPaymentMethodLabel}
        normalPaddlePrice={normalPaddlePrice}
        premiumPaddlePrice={premiumPaddlePrice}
        walletBalance={wallet}
        paddlePaymentMethod={paddlePaymentMethod}
        setPaddlePaymentMethod={setPaddlePaymentMethod}
        showApplePay={applePayVisible}
        paddleType={paddleType}
        setPaddleType={setPaddleType}
        canAffordNormalPaddle={canAffordNormalPaddle}
        canAffordPremiumPaddle={canAffordPremiumPaddle}
        buyingPaddle={buyingPaddle}
        canBuyPremiumInLive={canBuyPremiumInLive}
        normalWalletStatusMessage={normalWalletStatusMessage}
        premiumWalletStatusMessage={premiumWalletStatusMessage}
        hasWalletShortfall={hasWalletShortfall}
        normalShortfall={normalShortfall}
        premiumShortfall={premiumShortfall}
        formatAmount={formatAmount}
        onOpenTopUp={() => setShowTopUpModal(true)}
        onPurchasePaddle={(type) => {
          setPaddleType(type);
          void handlePurchasePaddle(type);
        }}
      />

      <TopUpModal
        isOpen={showTopUpModal}
        onOpenChange={setShowTopUpModal}
        defaultAmount={
          walletTopUpDefaultShortfall > 0
            ? walletTopUpDefaultShortfall
            : undefined
        }
        onSuccess={() => {
          setShowTopUpModal(false);
        }}
      />
      <PaymentGatewayModal
        isOpen={!!gatewayUrl}
        onClose={() => setGatewayUrl(null)}
        gatewayUrl={gatewayUrl || ""}
        isAr={isRtl}
      />
    </section>
  );
}
