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

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: res } = await api.get<ApiResponse<{ videos: GeneratedVideo[] }>>(
        '/api/videos/generated'
      );
      const payload = unwrap(res);
      const videos: GeneratedVideo[] = payload.videos || [];
      setGeneratedVideos(videos);

      // 只在明确指定 preferVideoId 时才自动选中
      // "__latest__" 表示选中最新的（第一个），用于新视频生成完成后
      // 其他值表示选中指定 ID 的视频
      // 不传则不设置选中项，由 useHomePersistence 恢复
      if (preferVideoId && videos.length > 0) {
        if (preferVideoId === "__latest__") {
          setSelectedVideoId(videos[0].id);
          setGeneratedVideo(resolveMediaUrl(videos[0].path));
          // 写入跨页面共享标记，让另一个页面也能感知最新生成的视频
          localStorage.setItem(`vigent_${storageKey}_latestGeneratedVideoId`, videos[0].id);
        } else {
          const found = videos.find(v => v.id === preferVideoId);
          if (found) {
            setSelectedVideoId(found.id);
            setGeneratedVideo(resolveMediaUrl(found.path));
          }
        }
      }
    } catch (error) {
      console.error("获取历史视频失败:", error);
    }
  }, [resolveMediaUrl, setGeneratedVideo, setSelectedVideoId]);

  // 【核心修复】当 selectedVideoId 变化时（例如从持久化恢复），自动同步 generatedVideo (URL)
  // 之前的逻辑只在 fetch 时设置，导致外部恢复 ID 后 URL 不同步
  useEffect(() => {
    if (!selectedVideoId || generatedVideos.length === 0) {
      // 如果没有选中 ID，或者列表为空，不要轻易置空 URL，除非明确需要
      // 这里保持现状，由 fetchGeneratedVideos 或 deleteVideo 处理置空
      return;
    }

    const video = generatedVideos.find(v => v.id === selectedVideoId);
    if (video) {
      const url = resolveMediaUrl(video.path);
      setGeneratedVideo(url);
    }
  }, [selectedVideoId, generatedVideos, resolveMediaUrl, setGeneratedVideo]);

  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) {
      toast.error("删除失败: " + error);
    }
  }, [fetchGeneratedVideos, selectedVideoId, setGeneratedVideo, setSelectedVideoId]);

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