import {
  type QueryKey,
  useMutation,
  useQueryClient,
} from '@tanstack/react-query';

import { useApiClient } from '@/lib/apiClient';

export type VideoModel =
  | 'higgsfield'
  | 'wan2.2-lightning'
  | 'sora-2'
  | 'fal-minimax-video-01'
  | 'fal-kling-v2.5-turbo-pro'
  | 'fal-luma-ray-2-flash'
  | 'fal-wan2.2-a14b-turbo'
  | 'fal-wan2.5'
  | 'fal-seedance-v1-pro';

interface StartVideoGenerationParams {
  generatedTextId?: string;
  generatedImageId?: string;
  uploadedImageId?: string;
  imageS3Filename?: string;
  clipId: string;
  prompt: string;
  quantity?: number;
  models?: VideoModel[];
}

interface UseStartVideoGenerationOptions {
  invalidateQueryKey?: QueryKey;
}

export function useStartVideoGeneration(
  options?: UseStartVideoGenerationOptions
) {
  const apiClient = useApiClient();
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: async (params: StartVideoGenerationParams) => {
      const requestBody = {
        generated_text_id: params.generatedTextId || undefined,
        generated_image_id: params.generatedImageId || undefined,
        uploaded_image_id: params.uploadedImageId || undefined,
        image_s3_filename: params.imageS3Filename || undefined,
        clip_id: params.clipId,
        prompt: params.prompt,
        quantity: params.quantity ?? 2,
        models: params.models ?? [],
      };

      const { data, error } = await apiClient.POST(
        '/api/video_gen/video/generate',
        {
          body: requestBody,
        }
      );

      if (error || !data) {
        throw new Error('Failed to start video generation');
      }

      return data;
    },
    onSuccess: () => {
      if (options?.invalidateQueryKey) {
        // Clear the cache so remounting fetches fresh data with new generation
        queryClient.removeQueries({
          queryKey: options.invalidateQueryKey,
        });
      }
    },
  });

  return mutation.mutateAsync;
}
