import { useCallback, useState } from "react";
import api from "@/shared/api/axios";
import { ApiResponse, unwrap } from "@/shared/api/types";

export interface BgmItem {
  id: string;
  name: string;
  ext?: string;
}

interface UseBgmOptions {

  selectedBgmId: string;
  setSelectedBgmId: React.Dispatch<React.SetStateAction<string>>;
}

export const useBgm = ({

  // selectedBgmId 用于参数类型推断，不在此 hook 内部直接使用
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  selectedBgmId,
  setSelectedBgmId,
}: UseBgmOptions) => {
  const [bgmList, setBgmList] = useState<BgmItem[]>([]);
  const [bgmLoading, setBgmLoading] = useState(false);
  const [bgmError, setBgmError] = useState<string>("");

  const fetchBgmList = useCallback(async () => {
    setBgmLoading(true);
    setBgmError("");
    try {
      const { data: res } = await api.get<ApiResponse<{ bgm: BgmItem[] }>>('/api/assets/bgm');
      const payload = unwrap(res);
      const items: BgmItem[] = Array.isArray(payload.bgm) ? payload.bgm : [];
      setBgmList(items);

      setSelectedBgmId((prev) => {
        if (prev && items.some((item) => item.id === prev)) return prev;
        return items[0]?.id || "";
      });
    } catch (error: unknown) {
      const axiosErr = error as { response?: { data?: { message?: string } }; message?: string };
      const message = axiosErr?.response?.data?.message || axiosErr?.message || '加载失败';
      setBgmError(message);
      setBgmList([]);
      console.error("获取背景音乐失败:", error);
    } finally {
      setBgmLoading(false);
    }
  }, [setSelectedBgmId]);

  return {
    bgmList,
    bgmLoading,
    bgmError,
    fetchBgmList,
  };
};
