import { createContext, useCallback, useMemo, useState } from 'react';

import {
  ModalTypes,
  PublishSongModalScreenType,
} from '@/components/modal/constants/ModalTypes';

export type ModalType =
  | ModalTypes.UPDATE_CLIP_METADATA
  | ModalTypes.PUBLISH_SONG
  | ModalTypes.GENERATE_COVER_ART;

/**
 * Individual generation item for carousel view
 */
export interface GenerationCarouselItem {
  id: string;
  clipId: string;
  title?: string; // Optional for now, placeholder
  createdAt: string;
  url: string;
  prompt: string;
  type: 'video' | 'image';
  isLiked: boolean;
  videoUploadId?: string | null; // Only populated for videos
}

/**
 * State for generation carousel view - browsing through generation items
 */
export interface GenerationCarouselState {
  items: GenerationCarouselItem[];
  initialIndex: number; // Which item to start at
  previousScreen: PublishSongModalScreenType; // Screen to return to when closing carousel
}

/**
 * Union type for all possible screen-specific state
 * Add new state types here as needed for other screens
 */
export type ScreenNavigationState = {
  generationCarousel?: GenerationCarouselState;
};

export const useSongModal = ({ modalType }: { modalType: ModalType }) => {
  const [currentScreen, setCurrentScreen] =
    useState<PublishSongModalScreenType>('main');
  const [navigationState, setNavigationState] = useState<ScreenNavigationState>(
    {}
  );

  const navigateTo = useCallback(
    (screen: PublishSongModalScreenType, state?: ScreenNavigationState) => {
      setCurrentScreen(screen);
      // Set new state if provided, otherwise clear it
      setNavigationState(state || {});
    },
    []
  );
  const title = useMemo(() => {
    if (modalType === ModalTypes.PUBLISH_SONG) {
      return 'Publish Song';
    } else if (modalType === ModalTypes.UPDATE_CLIP_METADATA) {
      return 'Edit Song Details';
    }
    return '';
  }, [modalType]);

  return useMemo(
    () => ({
      currentScreen,
      setCurrentScreen,
      navigateTo,
      navigationState,
      setNavigationState,
      title,
      modalType,
    }),
    [currentScreen, navigateTo, navigationState, title, modalType]
  );
};

const SongModalContext = createContext<ReturnType<typeof useSongModal>>(
  undefined as never
);

export default SongModalContext;
