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

import { useStores } from '@/app/(root)/AppProviders';
import { toast } from '@/components/toast/Toast';
import { components } from '@/lib/gen';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  handleRemixCoverAction,
  handleRemixExtendAction,
} from '@/utils/remixUtils';
import { isProjectsFeatureEnabled } from '@/utils/session';
import { encodeTimeFormat } from '@/utils/utils';

const AVAILABLE_REMIX_TYPES: components['schemas']['RemixAction'][] = [
  'cover',
  'extend',
];

export const useRemixUrlParams = () => {
  const { clips, genForm, session, createV2, project } = useStores();

  const router = useRouter();
  const searchParams = useSearchParams();

  const handleRemixUrlParams = useCallback(async () => {
    if (!searchParams || !session.sessionIsLoaded) {
      return;
    }

    // Handle remix_type parameter structure
    const songId = searchParams.get('song_id');
    if (!songId) {
      return;
    }

    const requestedRemixType = searchParams.get('remix_type');
    const style = searchParams.get('style'); // used for cover
    const lyrics = searchParams.get('lyrics'); // used for extend
    const extendFrom = searchParams.get('extend_from'); // used for extend
    const utmSource = searchParams.get('utm_source');

    const clip = await clips.loadClipById(songId);
    if (!clip) {
      return;
    }

    clips.updateClips([clip]);

    const isUserOwnClip = clip.user_id === session.user?.id;
    const isClipRemixable = clip.metadata?.can_remix;
    if (!isUserOwnClip && !isClipRemixable) {
      toast({
        title: 'Cannot remix',
        description: 'This song cannot be remixed.',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      return;
    }

    // Determine available remix types based on allowed_remix_actions
    // If user owns the clip, allow any remix action (bypass restrictions)
    const clipAllowedRemixActions = isUserOwnClip
      ? null
      : clip.allowed_remix_actions;
    if (clipAllowedRemixActions && clipAllowedRemixActions.length === 0) {
      toast({
        title: 'Cannot remix',
        description: 'No remix actions are allowed for this song.',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      return;
    }

    let remixType;
    if (!clipAllowedRemixActions) {
      remixType =
        (requestedRemixType as components['schemas']['RemixAction']) ||
        AVAILABLE_REMIX_TYPES[0];
    } else if (clipAllowedRemixActions && clipAllowedRemixActions.length > 0) {
      // Use the first available remix type that is allowed
      const allowedTypes = AVAILABLE_REMIX_TYPES.filter((action) =>
        clipAllowedRemixActions.includes(action)
      );

      // Check if no supported remix types are available
      if (allowedTypes.length === 0) {
        toast({
          title: 'Cannot remix',
          description:
            'No supported remix actions are available for this song.',
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
        return;
      }

      if (
        requestedRemixType &&
        allowedTypes.includes(
          requestedRemixType as components['schemas']['RemixAction']
        )
      ) {
        remixType = requestedRemixType;
      } else {
        remixType = allowedTypes[0];
      }
    }

    if (remixType === 'cover' && !genForm.coverClipId) {
      if (isProjectsFeatureEnabled(session)) {
        await project.setCurrentProjectToClipProject(clip);
      }
      // Handle cover action
      handleRemixCoverAction({
        clip,
        session,
        genForm,
        createV2,
        router,
        pathname: '/create',
      });

      if (style) {
        createV2.setTagInput(decodeURIComponent(style));
      }
    } else if (remixType === 'extend' && !genForm.continueClipId) {
      if (isProjectsFeatureEnabled(session)) {
        await project.setCurrentProjectToClipProject(clip);
      }
      // Handle extend action
      handleRemixExtendAction({
        clip,
        session,
        genForm,
        createV2,
        router,
        pathname: '/create',
      });

      if (lyrics) {
        const decodedLyrics = decodeURIComponent(lyrics);
        createV2.setActiveLyrics(decodedLyrics);
        genForm.setLyrics(decodedLyrics);
      }
      if (extendFrom) {
        const extendFromSeconds = parseFloat(extendFrom);
        if (!isNaN(extendFromSeconds)) {
          const timeFormat = encodeTimeFormat(extendFromSeconds);
          createV2.setActiveContinueAtSeconds(timeFormat);
          genForm.setContinueAtSeconds(extendFromSeconds);
        }
      }
    }

    logWebUserEvent({
      actionName: 'RemixDeepLinkVisited',
      context: {
        remixType: remixType as components['schemas']['RemixAction'],
        songId: songId,
        style: style,
        lyrics: lyrics,
        extendFrom: extendFrom,
        utmSource: utmSource || undefined,
      },
    });
  }, [
    searchParams,
    clips,
    genForm,
    session,
    session.sessionIsLoaded,
    createV2,
    router,
    project,
  ]);

  useEffect(() => {
    if (genForm.isLoading) {
      return;
    }

    handleRemixUrlParams();
  }, [genForm.isLoading, handleRemixUrlParams]);

  return { handleRemixUrlParams };
};
