import { useSearchParams } from 'next/navigation';
import { useEffect } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { toast } from '@/components/toast/Toast';
import { useApiClient } from '@/lib/apiClient';
import { downloadClipAudio, logDownloadToBilling } from '@/utils/download';

export const useCheckoutSuccessModals = () => {
  const { clips, menus } = useStores();
  const { session } = useStores();
  const apiClient = useApiClient();
  const searchParams = useSearchParams();

  useEffect(() => {
    const checkoutSessionId = searchParams.get('checkout_session_id');
    const commercialRightsCheckoutSessionId = searchParams.get(
      'commercial_rights_checkout_session_id'
    );
    const subscribedClipId = searchParams.get('subscribed_clip_id');
    const purchasedClipId = searchParams.get('purchased_clip_id');

    const showModalForClip = async (
      clipId: string,
      screen: 'successfullySubscribed' | 'rightsPurchased'
    ) => {
      try {
        const clip = await clips.loadClipById(clipId);

        const songTitle = clip?.title || 'Untitled';

        const downloadHandler = async () => {
          if (clip) {
            await downloadClipAudio(apiClient, clip, session);
            await logDownloadToBilling(apiClient, clip.id);
          }
        };

        if (screen === 'rightsPurchased') {
          menus.openCommercialRightsSuccessModal({
            title: 'Rights purchased',
            songTitle,
            onDownload: downloadHandler,
          });
        } else {
          menus.openSubscriptionSuccessModal({
            title: 'Successfully subscribed',
            songTitle,
            onDownload: downloadHandler,
          });
        }
      } catch (error) {
        console.error('Failed to fetch clip data:', error);
        toast({
          title: 'Download Error',
          description: 'Unable to download the clip. Please try again.',
          status: 'error',
        });
      }
    };

    if (subscribedClipId && checkoutSessionId) {
      showModalForClip(subscribedClipId, 'successfullySubscribed');

      const newSearchParams = new URLSearchParams(searchParams.toString());
      newSearchParams.delete('checkout_session_id');
      newSearchParams.delete('subscribed_clip_id');
      const newUrl =
        window.location.pathname +
        (newSearchParams.toString() ? `?${newSearchParams.toString()}` : '');
      window.history.replaceState({}, '', newUrl);
    } else if (purchasedClipId && commercialRightsCheckoutSessionId) {
      showModalForClip(purchasedClipId, 'rightsPurchased');

      const newSearchParams = new URLSearchParams(searchParams.toString());
      newSearchParams.delete('commercial_rights_checkout_session_id');
      newSearchParams.delete('purchased_clip_id');
      const newUrl =
        window.location.pathname +
        (newSearchParams.toString() ? `?${newSearchParams.toString()}` : '');
      window.history.replaceState({}, '', newUrl);
    }
  }, [searchParams, menus, clips, apiClient]);
};
