import { getAuctionGroups, getGroupAuctionById } from "@/actions/group-auctions";
import AnnualAuctionResultsVideoTableClient from "@/components/annaulMazad/AnnualAuctionResultsVideoTableClient";
import BookletDownloadCard from "@/components/annaulMazad/BookletDownloadCard";
import GroupAuctionLocationMapSection from "@/components/annaulMazad/GroupAuctionLocationMapSection";
import { metaObject } from "@/config/site.config";
import { getLocale, getTranslations } from "next-intl/server";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string; lang: string }>;
}) {
  const { id } = await params;
  const locale = await getLocale();
  const t = await getTranslations({
    locale,
    namespace: "ANNUAL_AUCTION_RESULTS",
  });
  let title = t("meta_title");

  try {
    const auction = await getGroupAuctionById(id);
    const auctionTitle = (auction as any)?.title;
    if (auctionTitle) {
      title = `${auctionTitle} - ${t("results_suffix")}`;
    }
  } catch {
    // ignore metadata fetch errors
  }

  return metaObject(
    title,
    t("meta_description"),
    undefined,
    undefined,
    `/annual-auctions/${id}/results`,
  );
}

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

export default async function AnnualAuctionResultsPage({ params }: Props) {
  const { id } = await params;
  const locale = await getLocale();
  const t = await getTranslations({
    locale,
    namespace: "ANNUAL_AUCTION_RESULTS",
  });

  const auction = await getGroupAuctionById(id);
  const roomsRes = await getAuctionGroups(id);
  // const innerItems = inner?.data?.data || [];
  const rooms = roomsRes?.data?.data || [];
  // const innerNextCursor = inner?.data?.meta?.next_cursor || null;
  const animalType = ((auction as any)?.animal_type || "horse").toString();
  const catalogUrl = (auction as any)?.catalog?.url as string | undefined;
  const maxAllowedDay = Number((auction as any)?.max_allowed_day);
  const maxDays = Number.isFinite(maxAllowedDay)
    ? Math.max(0, maxAllowedDay - 1)
    : 0;
  const isArabic = (locale || "").toLowerCase().startsWith("ar");
  const entityLabel = t(
    animalType === "camel" ? "entity.camel" : "entity.horse",
  );
  const toOptionalNumber = (value: unknown): number | null => {
    if (value === undefined || value === null || value === "") return null;
    const n = Number(value);
    return Number.isFinite(n) ? n : null;
  };
  const auctionStats = (auction as any)?.statistics || {};
  const auctionGroupStats = auctionStats?.auction_groups || {};

  const totalPaddles =
    toOptionalNumber(auctionStats?.paddles_count) ??
    toOptionalNumber((auction as any)?.paddles_count) ??
    toOptionalNumber((auction as any)?.paddle_count) ??
    toOptionalNumber((auction as any)?.total_paddles) ??
    0;

  const roomStatusCounts = (rooms as any[]).reduce(
    (acc, r) => {
      const s = String((r as any)?.status || "")
        .trim()
        .toLowerCase();
      if (s === "sold") acc.sold += 1;
      else if (s === "skipped") acc.skipped += 1;
      else if (s === "unsold") acc.unsold += 1;
      else if (s === "withdrawn" || s === "pulled") acc.withdrawn += 1;
      return acc;
    },
    { sold: 0, unsold: 0, withdrawn: 0, skipped: 0 },
  );

  const soldCount =
    toOptionalNumber(auctionGroupStats?.sold) ?? roomStatusCounts.sold;
  const unsoldCount =
    toOptionalNumber(auctionGroupStats?.unsold) ?? roomStatusCounts.unsold;
  const skippedCount =
    toOptionalNumber(auctionGroupStats?.skipped) ??
    roomStatusCounts.skipped;
  const withdrawnCount =
    toOptionalNumber(auctionGroupStats?.withdrawn) ??
    roomStatusCounts.withdrawn;
  const participatingCount =
    toOptionalNumber((auction as any)?.total_participating_animals) ??
    toOptionalNumber(auctionGroupStats?.total) ??
    toOptionalNumber((rooms as any[])?.length) ??
    0;

  const stats = [
    {
      label: t("stats.paddles"),
      value: totalPaddles,
      variant: "blue" as const,
      icon: "users" as const,
    },
    {
      label: t("stats.withdrawn", { entity: entityLabel }),
      value: withdrawnCount,
      variant: "blue" as const,
      icon: "withdrawn" as const,
    },
    {
      label: t("stats.participating", { entity: entityLabel }),
      value: participatingCount,
      variant: "blue" as const,
      icon: "gavel" as const,
    },
    {
      label: t("stats.unsold", { entity: entityLabel }),
      value: unsoldCount,
      variant: "orange" as const,
      icon: "unsold" as const,
    },
    {
      label: t("stats.skipped", { entity: entityLabel }),
      value: skippedCount,
      variant: "purple" as const,
      icon: "skipped" as const,
    },
    {
      label: t("stats.sold", { entity: entityLabel }),
      value: soldCount,
      variant: "green" as const,
      icon: "sold" as const,
    },
  ];
  const auctionType = String(
    (auction as any)?.auction_type || "",
  ).toLowerCase();
  const auctionTypeLabel =
    auctionType === "private" ? t("stats.private") : t("stats.public");
  const locationLabel = [
    ((auction as any)?.country || "").trim(),
    ((auction as any)?.state || "").trim(),
  ]
    .filter(Boolean)
    .join(" • ");

  const getLocalizedTitle = (title: string) => {
    try {
      const parsed = JSON.parse(title);
      return parsed[locale] || parsed["en"] || title;
    } catch {
      return title;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-[#F7FAF8] to-white text-slate-800">
      <main
        className="max-w-7xl mx-auto px-4 sm:px-6 py-6 space-y-6"
        dir={isArabic ? "rtl" : "ltr"}
      >
        <section className="rounded-xl bg-[#0F5132] shadow-[0_10px_30px_rgba(15,81,50,0.25)] p-5 sm:p-6">
          <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
            <div className="min-w-0">
              <div className="inline-flex items-center gap-2 rounded-full border border-white/30 bg-white/10 px-3 py-1 text-xs font-bold text-white">
                <span className="inline-block w-2 h-2 rounded-full bg-white" />
                {t("ended_badge")}
              </div>

              <h1 className="mt-3 text-2xl md:text-3xl font-extrabold text-white leading-tight">
                {getLocalizedTitle((auction as any)?.title) ||
                  t("title_fallback")}
              </h1>
              <p className="text-sm md:text-base text-white/90 mt-1">
                {t("subtitle_ended")}
              </p>

              <div className="mt-4 flex flex-wrap gap-2 text-xs sm:text-sm">
                {String((auction as any)?.unique_id || "").trim() ? (
                  <span className="inline-flex items-center rounded-full bg-white/15 border border-white/20 px-3 py-1 font-semibold text-white">
                    #{String((auction as any)?.unique_id)}
                  </span>
                ) : null}
                {locationLabel ? (
                  <span className="inline-flex items-center rounded-full bg-white/15 border border-white/20 px-3 py-1 font-medium text-white">
                    {t("stats.location")}: {locationLabel}
                  </span>
                ) : null}
                <span className="inline-flex items-center rounded-full bg-white/15 border border-white/20 px-3 py-1 font-medium text-white">
                  {t("stats.auction_type")}: {auctionTypeLabel}
                </span>
                <span className="inline-flex items-center rounded-full border border-white/30 bg-white/20 px-3 py-1 font-semibold text-white">
                  {t("rooms_title", { entity: entityLabel })}: {rooms.length}
                </span>
              </div>
            </div>

            {catalogUrl ? (
              <div className="shrink-0 w-fit">
                <BookletDownloadCard
                  catalogUrl={catalogUrl}
                  className="bg-white shadow-sm cursor-pointer border border-slate-200"
                  title={t("brochure_title")}
                  description={t("brochure_hint")}
                  downloadLabel={t("brochure_button")}
                />
              </div>
            ) : null}
          </div>
        </section>
        <AnnualAuctionResultsVideoTableClient
          groupId={String((auction as any)?.id)}
          rooms={rooms}
          // initialItems={innerItems}
          // initialNextCursor={innerNextCursor}
          maxDays={maxDays}
          animalType={animalType}
          auctionType={auction.auction_type}
          stats={stats as any}
          catalogUrl={catalogUrl}
          videos={(auction as any)?.videos}
          normalPaddlePrice={
            Number((auction as any)?.normal_paddle_price ?? 0) || undefined
          }
          premiumPaddlePrice={
            Number((auction as any)?.premium_paddle_price ?? 0) || undefined
          }
        />

        <GroupAuctionLocationMapSection
          lat={(auction as any)?.lat}
          lng={(auction as any)?.lng}
        />
      </main>
    </div>
  );
}
