import { useCallback, useState } from "react";
import api from "@/lib/axios";

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

interface UseBgmOptions {
  storageKey: string;
  selectedBgmId: string;
  setSelectedBgmId: React.Dispatch<React.SetStateAction<string>>;
}

export const useBgm = ({
  storageKey,
  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 } = await api.get('/api/assets/bgm');
      const items: BgmItem[] = Array.isArray(data.bgm) ? data.bgm : [];
      setBgmList(items);

      const savedBgmId = localStorage.getItem(`vigent_${storageKey}_bgmId`);
      setSelectedBgmId((prev) => {
        if (prev && items.some((item) => item.id === prev)) return prev;
        if (savedBgmId && items.some((item) => item.id === savedBgmId)) return savedBgmId;
        return items[0]?.id || "";
      });
    } catch (error: any) {
      const message = error?.response?.data?.detail || error?.message || '加载失败';
      setBgmError(message);
      setBgmList([]);
      console.error("获取背景音乐失败:", error);
    } finally {
      setBgmLoading(false);
    }
  }, [setSelectedBgmId, storageKey]);

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