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

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

interface UseRefAudiosOptions {
  fixedRefText: string;
  selectedRefAudio: RefAudio | null;
  setSelectedRefAudio: React.Dispatch<React.SetStateAction<RefAudio | null>>;
  setRefText: React.Dispatch<React.SetStateAction<string>>;
}

export const useRefAudios = ({
  fixedRefText,
  selectedRefAudio,
  setSelectedRefAudio,
  setRefText,
}: UseRefAudiosOptions) => {
  const [refAudios, setRefAudios] = useState<RefAudio[]>([]);
  const [isUploadingRef, setIsUploadingRef] = useState(false);
  const [uploadRefError, setUploadRefError] = useState<string | null>(null);

  const fetchRefAudios = useCallback(async () => {
    try {
      const { data } = await api.get('/api/ref-audios');
      const items: RefAudio[] = data.items || [];
      items.sort((a, b) => b.created_at - a.created_at);
      setRefAudios(items);
    } catch (error) {
      console.error("获取参考音频失败:", error);
    }
  }, []);

  const uploadRefAudio = useCallback(async (file: File) => {
    const refTextInput = fixedRefText;

    setIsUploadingRef(true);
    setUploadRefError(null);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('ref_text', refTextInput);

      const { data } = await api.post('/api/ref-audios', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });

      await fetchRefAudios();
      setSelectedRefAudio(data);
      setRefText(data.ref_text);
      setIsUploadingRef(false);
    } catch (err: any) {
      console.error("Upload ref audio failed:", err);
      setIsUploadingRef(false);
      const errorMsg = err.response?.data?.detail || err.message || String(err);
      setUploadRefError(`上传失败: ${errorMsg}`);
    }
  }, [fetchRefAudios, fixedRefText, setRefText, setSelectedRefAudio]);

  const deleteRefAudio = useCallback(async (audioId: string) => {
    if (!confirm("确定要删除这个参考音频吗？")) return;
    try {
      await api.delete(`/api/ref-audios/${encodeURIComponent(audioId)}`);
      fetchRefAudios();
      if (selectedRefAudio?.id === audioId) {
        setSelectedRefAudio(null);
        setRefText('');
      }
    } catch (error) {
      alert("删除失败: " + error);
    }
  }, [fetchRefAudios, selectedRefAudio, setRefText, setSelectedRefAudio]);

  return {
    refAudios,
    isUploadingRef,
    uploadRefError,
    setUploadRefError,
    fetchRefAudios,
    uploadRefAudio,
    deleteRefAudio,
  };
};
