import { useMemo } from "react";
import { useQuery, useConvexAuth } from "convex/react";
import type { FunctionReference } from "convex/server";
import type { SidebarInitialData } from "@/components/sidebar/types";
import type { MediaAsset } from "@/types/media";
import { api } from "@/lib/convex/api";
import {
  mapSidebarDatasetListQueryResultToInitialData,
  type SidebarDatasetListQueryResult,
} from "@/lib/sidebar-data";
import { toBrowserAccessibleUrl } from "@/lib/url/browser-file-url";

const sidebarDatasetListQuery = ((api as unknown as Record<string, unknown>).sidebar as
  | Record<string, unknown>
  | undefined)?.datasetList as FunctionReference<
  "query",
  "public",
  { workspaceId: string },
  SidebarDatasetListQueryResult
>;

export interface ConvexSidebarDataResult {
  data: SidebarInitialData | null;
  isLoading: boolean;
  isAuthLoading: boolean;
  isAuthenticated: boolean;
  hasLiveSubscription: boolean;
  canUseHttpFallback: boolean;
  error: Error | null;
  refetch: () => Promise<void>;
}

/**
 * Convex 模式下的侧边栏数据 hook
 * 使用 Convex 的 useQuery 实现实时订阅，无需手动 refetch
 *
 * 注意：此 hook 仅应在 Convex 模式下使用
 * 后端从 ctx.auth.getUserIdentity() 获取用户身份，前端无需传入 userId
 */
export function useConvexSidebarData(workspaceId: string): ConvexSidebarDataResult {
  const { isAuthenticated, isLoading: isAuthLoading } = useConvexAuth();

  // 显式转为 boolean，确保类型正确
  const shouldFetch = Boolean(isAuthenticated && workspaceId);
  const sidebarDataset = useQuery(
    sidebarDatasetListQuery,
    shouldFetch ? { workspaceId } : "skip",
  );

  const normalizeAssetUrls = (asset: MediaAsset): MediaAsset => {
    const fileUrl = toBrowserAccessibleUrl(asset.file_url) ?? asset.file_url;
    const thumbUrl = toBrowserAccessibleUrl(asset.thumbnail_url) ?? asset.thumbnail_url;
    return { ...asset, file_url: fileUrl, thumbnail_url: thumbUrl };
  };

  const normalizedSidebarDataset = useMemo<SidebarDatasetListQueryResult | null>(() => {
    if (sidebarDataset === undefined || !sidebarDataset) {
      return null;
    }

    return {
      ...sidebarDataset,
      media_assets: ((sidebarDataset.media_assets ?? []) as MediaAsset[]).map(normalizeAssetUrls),
      trashed_media_assets: ((sidebarDataset.trashed_media_assets ?? []) as MediaAsset[]).map(
        normalizeAssetUrls,
      ),
      mindmap_assets: ((sidebarDataset.mindmap_assets ?? []) as MediaAsset[]).map(normalizeAssetUrls),
      trashed_mindmap_assets: ((sidebarDataset.trashed_mindmap_assets ?? []) as MediaAsset[]).map(
        normalizeAssetUrls,
      ),
      table_assets: ((sidebarDataset.table_assets ?? []) as MediaAsset[]).map(normalizeAssetUrls),
      trashed_table_assets: ((sidebarDataset.trashed_table_assets ?? []) as MediaAsset[]).map(
        normalizeAssetUrls,
      ),
    };
  }, [sidebarDataset]);

  // 组合数据，格式与 SidebarInitialData 一致
  const data: SidebarInitialData | null = useMemo(() => {
    if (!normalizedSidebarDataset) {
      return null;
    }
    return mapSidebarDatasetListQueryResultToInitialData(normalizedSidebarDataset);
  }, [normalizedSidebarDataset]);

  // loading 状态：只有当 shouldFetch 为 true 且数据未加载时才算 loading
  // 使用 === undefined 判断，因为 skip 时返回 undefined
  const isLoading = shouldFetch && sidebarDataset === undefined;
  const error = null;
  const hasLiveSubscription = shouldFetch;
  const canUseHttpFallback = Boolean(workspaceId) && !isAuthLoading && !isAuthenticated;

  // Convex 模式下数据自动实时同步，refetch 保持空操作以兼容旧接口。
  const refetch = async () => {
    // 空操作 - Convex 会自动同步数据
  };

  return {
    data,
    isLoading,
    isAuthLoading,
    isAuthenticated,
    hasLiveSubscription,
    canUseHttpFallback,
    error,
    refetch,
  };
}
