import { useParams, usePathname, useSearchParams } from 'next/navigation';
import { useEffect, useRef } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { toast } from '@/components/toast/Toast';
import { useApiClient } from '@/lib/apiClient';
import { SHAREABLE_CONTENT_TYPE_PATH_PREFIXES } from '@/utils/share';
import { getContentTypeFromPath } from '@/utils/share';

/**
 * Track the share count
 */
export default function useShareTracking() {
  const pathname = usePathname();
  const params = useParams();
  const searchParams = useSearchParams();
  const apiClient = useApiClient();
  const { session } = useStores();

  // Track which share IDs have been processed to prevent duplicates
  const processedShareIds = useRef(new Set<string>());

  useEffect(() => {
    const isShareTrackedPage = SHAREABLE_CONTENT_TYPE_PATH_PREFIXES.some(
      (prefix: string) => pathname.startsWith(prefix)
    );
    if (isShareTrackedPage) {
      const contentType = getContentTypeFromPath(pathname);
      const contentId = params.slug as string;
      // Track the page visit for analytics
      if (contentType && contentId) {
        const shareId = searchParams.get('sh');
        if (shareId && contentType === 'song') {
          apiClient.POST('/api/gen/{gen_id}/increment_action_count/', {
            params: { path: { gen_id: contentId } },
            body: {
              action: 'visit',
              share_id: shareId,
            },
          });

          // Only create share event if session is loaded and we haven't processed this shareId yet
          if (
            session.sessionIsLoaded &&
            session.user?.handle &&
            !processedShareIds.current.has(shareId)
          ) {
            processedShareIds.current.add(shareId);

            const createShareEvent = async () => {
              try {
                const response = await apiClient.POST('/api/share/event', {
                  body: {
                    share_id: shareId,
                    recipient: session.user.handle,
                    send_notification: false,
                  },
                });

                if (response.data?.success) {
                  toast({
                    title: 'Added to My Sharelist',
                    status: 'success',
                    duration: 2000,
                    isClosable: true,
                  });
                }
              } catch (error) {
                console.error('Failed to create share event:', error);
              }
            };

            void createShareEvent();
          }
        }
      }
    }
  }, [
    pathname,
    params.slug,
    searchParams,
    apiClient,
    session.sessionIsLoaded,
    session.user,
  ]);
}
