import { useClerk } from '@clerk/nextjs';
import { useCallback, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { getClerkSignInRedirectProps } from '@/utils/utils';

export default function useFollowUser(
  handle: string,
  initialIsFollowing: boolean,
  options?: {
    contextType?: string;
    recommendationItemId?: string;
    hookId?: string;
  }
) {
  const { contextType, recommendationItemId, hookId } = options || {};
  const { session } = useStores();
  const clerk = useClerk();
  const [isFollowing, setIsFollowing] = useState(initialIsFollowing);
  const updateFollowing = useCallback(
    async (newIsFollowing: boolean) => {
      if (!session.user) {
        return clerk.openSignIn({
          withSignUp: true,
          ...getClerkSignInRedirectProps(`/profile/${handle}`),
        });
      } else {
        setIsFollowing(newIsFollowing);
        await session.apiClient.POST('/api/profiles/follow', {
          body: {
            unfollow: !newIsFollowing,
            handle: handle,
            recommendation_metadata: {
              context_type: contextType,
              hook_id: hookId,
              recommendation_item_id: recommendationItemId,
            },
          },
        });
      }
    },
    [session, clerk, handle, contextType, recommendationItemId, hookId]
  );

  return {
    isFollowing,
    setIsFollowing: updateFollowing,
  };
}
