import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '../lib/api';

// Live Blog Queries
export function useLiveBlogs(params: api.FindLiveBlogsParams = {}) {
  return useQuery({
    queryKey: ['liveBlogs', params],
    queryFn: () => api.fetchLiveBlogs(params),
  });
}

export function useLiveBlog(slug: string) {
  return useQuery({
    queryKey: ['liveBlog', slug],
    queryFn: () => api.fetchLiveBlogBySlug(slug),
    enabled: !!slug,
    refetchOnWindowFocus: true,
    refetchOnMount: true,
  });
}

export function useLiveBlogById(id: string) {
  return useQuery({
    queryKey: ['liveBlog', id],
    queryFn: () => api.fetchLiveBlogById(id),
    enabled: !!id,
  });
}

export function useLiveBlogUpdates(liveBlogId: string, page = 1, limit = 50) {
  return useQuery({
    queryKey: ['liveBlogUpdates', liveBlogId, page, limit],
    queryFn: () => api.fetchLiveBlogUpdates(liveBlogId, page, limit),
    enabled: !!liveBlogId,
    refetchInterval: 10000, // Poll every 10 seconds as fallback
  });
}

export function useRecentLiveBlogs() {
  return useQuery({
    queryKey: ['recentLiveBlogs'],
    queryFn: () => api.fetchRecentLiveBlogs(),
    refetchInterval: 30000, // Refetch every 30 seconds
  });
}

export function usePinnedLiveBlogs() {
  return useQuery({
    queryKey: ['pinnedLiveBlogs'],
    queryFn: () => api.fetchPinnedLiveBlogs(),
    refetchInterval: 30000, // Refetch every 30 seconds
  });
}

export function useActiveLiveBlogs() {
  return useQuery({
    queryKey: ['activeLiveBlogs'],
    queryFn: () => api.fetchActiveLiveBlogs(),
    refetchInterval: 10000, // Refetch every 10 seconds for ticker
  });
}

// Live Blog Mutations (Admin)
export function useCreateLiveBlogUpdate() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ liveBlogId, dto }: { liveBlogId: string; dto: api.CreateLiveBlogUpdateDto }) =>
      api.createLiveBlogUpdate(liveBlogId, dto),
     onSuccess: (_data, variables) => {
      // Invalidate live blog queries
      queryClient.invalidateQueries({ queryKey: ['liveBlog', variables.liveBlogId] });
      queryClient.invalidateQueries({ queryKey: ['liveBlogUpdates', variables.liveBlogId] });
    },
  });
}

export function useUpdateLiveBlogUpdate() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ liveBlogId, updateId, dto }: { 
      liveBlogId: string; 
      updateId: string; 
      dto: api.UpdateLiveBlogUpdateDto 
    }) => api.updateLiveBlogUpdate(liveBlogId, updateId, dto),
     onSuccess: (_data, variables) => {
      // Invalidate live blog queries
      queryClient.invalidateQueries({ queryKey: ['liveBlog', variables.liveBlogId] });
      queryClient.invalidateQueries({ queryKey: ['liveBlogUpdates', variables.liveBlogId] });
    },
  });
}

export function useDeleteLiveBlogUpdate() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ liveBlogId, updateId }: { liveBlogId: string; updateId: string }) =>
      api.deleteLiveBlogUpdate(liveBlogId, updateId),
     onSuccess: (_data, variables) => {
      // Invalidate live blog queries
      queryClient.invalidateQueries({ queryKey: ['liveBlog', variables.liveBlogId] });
      queryClient.invalidateQueries({ queryKey: ['liveBlogUpdates', variables.liveBlogId] });
    },
  });
}

// Live Blog CRUD Mutations
export function useCreateLiveBlog() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (dto: api.CreateLiveBlogDto) => api.createLiveBlog(dto),
    onSuccess: () => {
      // Invalidate all live blogs queries
      queryClient.invalidateQueries({ queryKey: ['liveBlogs'] });
      queryClient.invalidateQueries({ queryKey: ['recentLiveBlogs'] });
    },
  });
}

export function useUpdateLiveBlog() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: api.UpdateLiveBlogDto }) =>
      api.updateLiveBlog(id, dto),
    onSuccess: () => {
      // Force immediate refetch of all live blog queries
      queryClient.invalidateQueries({ 
        queryKey: ['liveBlog'], 
        refetchType: 'active' 
      });
      queryClient.invalidateQueries({ 
        queryKey: ['liveBlogs'], 
        refetchType: 'active' 
      });
      queryClient.invalidateQueries({ 
        queryKey: ['recentLiveBlogs'], 
        refetchType: 'active' 
      });
    },
  });
}

export function useDeleteLiveBlog() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.deleteLiveBlog(id),
    onSuccess: () => {
      // Invalidate all live blogs queries
      queryClient.invalidateQueries({ queryKey: ['liveBlogs'] });
      queryClient.invalidateQueries({ queryKey: ['recentLiveBlogs'] });
    },
  });
}

export function useArchiveLiveBlog() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.archiveLiveBlog(id),
    onSuccess: () => {
      // Invalidate all live blogs queries
      queryClient.invalidateQueries({ queryKey: ['liveBlogs'] });
      queryClient.invalidateQueries({ queryKey: ['recentLiveBlogs'] });
    },
  });
}

export function usePublishLiveBlog() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, status = 'draft' }: { id: string; status?: 'draft' | 'live' | 'ended' }) => 
      api.publishLiveBlog(id, status),
    onSuccess: () => {
      // Invalidate all live blogs queries
      queryClient.invalidateQueries({ queryKey: ['liveBlogs'] });
      queryClient.invalidateQueries({ queryKey: ['recentLiveBlogs'] });
    },
  });
}