"use client";

import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

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";
import type { AdminDrawShowData } from "@/types/api/admin-draws";

export function RiskDrawHeader({ drawId }: { drawId: number }) {
  const { t } = useTranslation(["risk", "draws"]);
  const [draw, setDraw] = useState<AdminDrawShowData | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setError(null);
    try {
      const d = await getAdminDraw(drawId);
      setDraw(d);
    } catch (e) {
      const msg =
        e instanceof LotteryApiBizError ? e.message : t("drawInfoLoadFailed");
      setError(msg);
      setDraw(null);
    }
  }, [drawId, t]);

  useEffect(() => {
    queueMicrotask(() => {
      void load();
    });
  }, [load]);

  if (error) {
    return <p className="text-sm text-destructive">{error}</p>;
  }

  if (!draw) {
    return <p className="text-sm text-muted-foreground">{t("loadingDraw")}</p>;
  }

  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>
  );
}
