import { useCallback, useEffect, useRef, useState } from "react";
import type { BgmItem } from "@/features/home/model/useBgm";
import { toast } from "sonner";

interface RefAudio {
  id: string;
  name: string;
  path: string;
  ref_text: string;
  duration_sec: number;
  created_at: number;
}

interface UseMediaPlayersOptions {
  bgmVolume: number;
  resolveBgmUrl: (bgmId?: string | null) => string | null;
  resolveMediaUrl: (url?: string | null) => string | null;
  setSelectedBgmId: React.Dispatch<React.SetStateAction<string>>;
  setEnableBgm: React.Dispatch<React.SetStateAction<boolean>>;
}

export const useMediaPlayers = ({
  bgmVolume,
  resolveBgmUrl,
  resolveMediaUrl,
  setSelectedBgmId,
  setEnableBgm,
}: UseMediaPlayersOptions) => {
  const [playingAudioId, setPlayingAudioId] = useState<string | null>(null);
  const [playingBgmId, setPlayingBgmId] = useState<string | null>(null);
  const audioPlayerRef = useRef<HTMLAudioElement | null>(null);
  const bgmPlayerRef = useRef<HTMLAudioElement | null>(null);

  const stopAudio = useCallback(() => {
    if (audioPlayerRef.current) {
      audioPlayerRef.current.pause();
      audioPlayerRef.current.currentTime = 0;
      audioPlayerRef.current = null;
    }
    setPlayingAudioId(null);
  }, []);

  const stopBgm = useCallback(() => {
    if (bgmPlayerRef.current) {
      bgmPlayerRef.current.pause();
      bgmPlayerRef.current.currentTime = 0;
      bgmPlayerRef.current = null;
    }
    setPlayingBgmId(null);
  }, []);

  const togglePlayPreview = useCallback((audio: RefAudio, e: React.MouseEvent) => {
    e.stopPropagation();

    if (bgmPlayerRef.current) {
      stopBgm();
    }

    if (playingAudioId === audio.id) {
      stopAudio();
      return;
    }

    stopAudio();

    const audioUrl = resolveMediaUrl(audio.path) || audio.path;
    if (!audioUrl) {
      toast.error("无法播放该参考音频");
      return;
    }
    const player = new Audio(audioUrl);
    player.onended = () => setPlayingAudioId(null);
    player.play().catch((err) => toast.error("播放失败: " + err));
    audioPlayerRef.current = player;
    setPlayingAudioId(audio.id);
  }, [playingAudioId, resolveMediaUrl, stopAudio, stopBgm]);

  const toggleBgmPreview = useCallback((bgm: BgmItem, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedBgmId(bgm.id);
    setEnableBgm(true);

    const bgmUrl = resolveBgmUrl(bgm.id);
    if (!bgmUrl) {
      toast.error("无法播放该背景音乐");
      return;
    }

    if (playingBgmId === bgm.id) {
      stopBgm();
      return;
    }

    stopAudio();
    stopBgm();

    const player = new Audio(bgmUrl);
    player.volume = Math.max(0, Math.min(bgmVolume, 1));
    player.onended = () => setPlayingBgmId(null);
    player.play().catch((err) => toast.error("播放失败: " + err));
    bgmPlayerRef.current = player;
    setPlayingBgmId(bgm.id);
  }, [bgmVolume, playingBgmId, resolveBgmUrl, setEnableBgm, setSelectedBgmId, stopAudio, stopBgm]);

  useEffect(() => {
    if (bgmPlayerRef.current) {
      bgmPlayerRef.current.volume = Math.max(0, Math.min(bgmVolume, 1));
    }
  }, [bgmVolume]);

  return {
    playingAudioId,
    playingBgmId,
    togglePlayPreview,
    toggleBgmPreview,
  };
};
