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

interface GeneratedVideo {
  id: string;
  name: string;
  path: string;
  size_mb: number;
  created_at: number;
}

interface UseGeneratedVideosOptions {
  storageKey: string;
  selectedVideoId: string | null;
  setSelectedVideoId: React.Dispatch<React.SetStateAction<string | null>>;
  setGeneratedVideo: React.Dispatch<React.SetStateAction<string | null>>;
  resolveMediaUrl: (url?: string | null) => string | null;
}

export const useGeneratedVideos = ({
  storageKey,
  selectedVideoId,
  setSelectedVideoId,
  setGeneratedVideo,
  resolveMediaUrl,
}: UseGeneratedVideosOptions) => {
  const [generatedVideos, setGeneratedVideos] = useState<GeneratedVideo[]>([]);

  const fetchGeneratedVideos = useCallback(async (preferVideoId?: string) => {
    try {
      const { data } = await api.get('/api/videos/generated');
      const videos: GeneratedVideo[] = data.videos || [];
      setGeneratedVideos(videos);

      const savedSelectedVideoId = localStorage.getItem(`vigent_${storageKey}_selectedVideoId`);
      const currentId = preferVideoId || selectedVideoId || savedSelectedVideoId || null;
      let nextId: string | null = null;
      let nextUrl: string | null = null;

      if (currentId) {
        const found = videos.find(v => v.id === currentId);
        if (found) {
          nextId = found.id;
          nextUrl = resolveMediaUrl(found.path);
        }
      }

      if (!nextId && videos.length > 0) {
        nextId = videos[0].id;
        nextUrl = resolveMediaUrl(videos[0].path);
      }

      if (nextId) {
        setSelectedVideoId(nextId);
        setGeneratedVideo(nextUrl);
      }
    } catch (error) {
      console.error("获取历史视频失败:", error);
    }
  }, [resolveMediaUrl, selectedVideoId, setGeneratedVideo, setSelectedVideoId, storageKey]);

  const deleteVideo = useCallback(async (videoId: string) => {
    if (!confirm("确定要删除这个视频吗？")) return;
    try {
      await api.delete(`/api/videos/generated/${videoId}`);
      if (selectedVideoId === videoId) {
        setSelectedVideoId(null);
        setGeneratedVideo(null);
      }
      fetchGeneratedVideos();
    } catch (error) {
      alert("删除失败: " + error);
    }
  }, [fetchGeneratedVideos, selectedVideoId, setGeneratedVideo, setSelectedVideoId]);

  return {
    generatedVideos,
    fetchGeneratedVideos,
    deleteVideo,
  };
};
