"use client";

import { useRouter } from "next/navigation";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";

import { getAdminDrawResultBatches } from "@/api/admin-draws";
import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { AdminLoadingState } from "@/components/admin/admin-loading-state";
import { DrawPublishDialog } from "@/modules/draws/draw-publish-dialog";
import { useDrawDetail } from "@/modules/draws/draw-detail-context";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawBatchesData } from "@/types/api/admin-draws";

/** 深链兼容：/publish/[batchId] 直接打开发布弹窗 */
export function DrawPublishConsole({ drawId, batchId }: { drawId: string; batchId: string }): React.ReactElement {
  const { t } = useTranslation(["draws", "common"]);
  const tRef = useTranslationRef(["draws", "common"]);
  const router = useRouter();
  const { refresh: refreshDraw } = useDrawDetail();
  const idNum = Number(drawId);
  const batchNum = Number(batchId);
  const [data, setData] = useState<AdminDrawBatchesData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (!Number.isFinite(idNum)) {
      setError(tRef.current("invalidDrawId"));
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      setData(await getAdminDrawResultBatches(idNum));
    } catch (e) {
      setData(null);
      setError(e instanceof LotteryApiBizError ? e.message : tRef.current("errors.loadFailed", { ns: "common" }));
    } finally {
      setLoading(false);
    }
  }, [idNum, tRef]);

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

  const batch = useMemo(() => {
    if (!Number.isFinite(batchNum)) return undefined;
    return data?.batches.find((b) => b.id === batchNum);
  }, [batchNum, data]);

  if (loading && !data) {
    return <AdminLoadingState minHeight="6rem" className="py-6" />;
  }

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

  if (!batch) {
    return <AdminNoResourceState message={t("batchNotFound")} />;
  }

  return (
    <DrawPublishDialog
      open
      onOpenChange={(open) => {
        if (!open) {
          router.replace(`/admin/draws/${drawId}/review`);
        }
      }}
      drawId={idNum}
      batch={batch}
      onPublished={() => {
        void refreshDraw();
        router.replace(`/admin/draws/${drawId}/results`);
      }}
      onDiscarded={() => {
        void refreshDraw();
        router.replace(`/admin/draws/${drawId}/review`);
      }}
    />
  );
}