import LiveRoomsTable from "@/components/annaulMazad/LiveRoomsTable";
import {
  getAuctionGroups,
  getGroupAuctionById,
  getDashboardGroupSingleAuctions,
} from "@/actions/group-auctions";
import { getLocale } from "next-intl/server";
import MyGroupAuctionHorsesTable from "@/components/dashboard/MyGroupAuctionHorsesTable";

type Props = {
  params: Promise<{ id: string; lang: string }>;
};

export default async function MyGroupAuctionParticipationDetailsPage({
  params,
}: Props) {
  const { id, lang } = await params;
  await getLocale();

  const isAr = (lang || "").toLowerCase().startsWith("ar");
  const backLabel = isAr ? "رجوع" : "Back";
  const pageTitle = isAr ? "تفاصيل مشاركتي" : "My Participation";
  const arrow = isAr ? "→" : "←";

  const auction = await getGroupAuctionById(id);

  const maxAllowedDay = Number((auction as any)?.max_allowed_day);
  const maxDays = Number.isFinite(maxAllowedDay)
    ? Math.max(0, maxAllowedDay - 1)
    : 0;

  const animalTypeRaw = String(
    (auction as any)?.animal_type || "camel",
  ).toLowerCase();
  const animalType = animalTypeRaw === "horse" ? "horse" : "camel";

  // كل عينات المزاد (خيل أو إبل) لمحتوى المجموعة
  const singleItemsRes = await getDashboardGroupSingleAuctions(id);
  const singleItems = singleItemsRes?.data?.data || [];

  const roomsRes = animalType === "camel" ? await getAuctionGroups(id) : null;
  const rooms = (roomsRes as any)?.data?.data || [];

  return (
    <div className="max-w-7xl mx-auto px-6 py-8">
      <div className="flex items-center justify-between flex-wrap gap-3 mb-6">
        <div className="flex items-center gap-3">
          <a
            href={`/${lang}/dashboard?tab=mazayadaty`}
            className="inline-flex items-center gap-2 text-sm font-semibold text-slate-700 hover:text-slate-900"
          >
            <span aria-hidden>{arrow}</span>
            <span>{backLabel}</span>
          </a>
          <h1 className="text-xl md:text-2xl font-extrabold text-slate-900">
            {pageTitle}
          </h1>
        </div>
      </div>

      <div className="space-y-6">
        {animalType === "camel" && (
          <LiveRoomsTable
            groupId={String((auction as any)?.id || id)}
            initialRooms={rooms}
            maxDays={maxDays}
            animalType={animalType}
            auctionType={(auction as any)?.auction_type}
          />
        )}

        {animalType === "horse" && (
          <MyGroupAuctionHorsesTable items={singleItems} groupAuctionId={id} />
        )}
      </div>
    </div>
  );
}
