import { getLikeStatus, thmubObject } from '@/services/editor';
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { authKeys } from '@/lib/query-keys';
import { LikeObjectParamsType, LikeType } from '@/services/editor/type';
import { useAsyncFn } from '../tools';
import { useCurrentUser } from '../auth';

export function useThmubObject(props: Pick<LikeObjectParamsType, 'objectId' | 'objectType'>) {
  const [thumb, setThumb] = useState<LikeType>();
  const { data: user } = useCurrentUser();

  const { data: likeStatus, refetch: refetchLikeStatus } = useQuery({
    queryKey: ['likeStatus', props.objectId, user?.userId],
    enabled: !!props.objectId && !!user?.userId,
    queryFn: async () => {
      const { data } = await getLikeStatus({ objectId: props.objectId, userId: user?.userId });
      return data.likeStatus;
    },
  });

  useEffect(() => {
    if (typeof likeStatus === 'number') {
      setThumb(likeStatus);
    }
  }, [likeStatus]);

  const { run: handleThumb, loading } = useAsyncFn(async (likeType: LikeType) => {
    setThumb(likeType);
    const { code } = await thmubObject({ ...props, likeType, userId: user?.userId });
    if (code === 200) {
      refetchLikeStatus();
    }
  });

  return {
    thumb,
    loading,
    handleThumb,
  };
}
