"use client";
import { AdminLoadingInline } from "@/components/admin/admin-loading-state";

import { useTranslation } from "react-i18next";
import { useTranslationRef } from "@/hooks/use-translation-ref";
import { useApiQuery } from "@/hooks/use-api-query";

import { getAdminDraw } from "@/api/admin-draws";
import { drawStatusLabel, hallPreviewDiffersFromDbStatus } from "@/modules/draws/draw-display";
import { DrawStatusBadge } from "@/modules/draws/draw-status-badge";
import { LotteryApiBizError } from "@/types/api/errors";

export function RiskDrawHeader({ drawId }: { drawId: number }) {
  const { t } = useTranslation(["risk", "draws"]);
  const tRef = useTranslationRef(["risk", "draws"]);

  const { data: draw, error } = useApiQuery(
    ["admin/draws", drawId],
    () => getAdminDraw(drawId),
  );

  if (error) {
    const msg =
      error instanceof LotteryApiBizError ? error.message : tRef.current("drawInfoLoadFailed");
    return <p className="text-sm text-destructive">{msg}</p>;
  }

  if (!draw) {
    return <AdminLoadingInline className="py-4" label={t("loadingDraw")} />;
  }

  return (
    <div className="mb-4 space-y-1">
      <h1 className="text-xl font-semibold tracking-tight">
        {t("headerTitle", { drawNo: draw.draw_no })}
      </h1>
      <p className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
        <span>{t("databaseStatus")}</span>
        <DrawStatusBadge
          status={draw.status}
          label={drawStatusLabel(draw.status, t)}
        />
        {hallPreviewDiffersFromDbStatus(draw.status, draw.hall_preview_status) ? (
          <>
            <span>{t("hallPreviewStatusLabel", { ns: "draws" })}</span>
            <DrawStatusBadge
              status={draw.hall_preview_status}
              label={drawStatusLabel(draw.hall_preview_status, t)}
            />
          </>
        ) : null}
      </p>
    </div>
  );
}
