"use client";

import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import { getAdminDraw } from "@/api/admin-draws";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawShowData } from "@/types/api/admin-draws";

type DrawDetailContextValue = {
  drawId: number;
  draw: AdminDrawShowData | null;
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
};

const DrawDetailContext = createContext<DrawDetailContextValue | null>(null);

export function DrawDetailProvider({
  drawId,
  children,
}: {
  drawId: string;
  children: ReactNode;
}): React.ReactElement {
  const tRef = useTranslationRef(["draws", "common"]);
  const idNum = Number(drawId);
  const [draw, setDraw] = useState<AdminDrawShowData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  const value = useMemo(
    () => ({ drawId: idNum, draw, loading, error, refresh }),
    [draw, error, idNum, loading, refresh],
  );

  return <DrawDetailContext.Provider value={value}>{children}</DrawDetailContext.Provider>;
}

export function useDrawDetail(): DrawDetailContextValue {
  const ctx = useContext(DrawDetailContext);
  if (ctx == null) {
    throw new Error("useDrawDetail must be used within DrawDetailProvider");
  }
  return ctx;
}