'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { FreeScoutTicket, TicketStatus, TicketPriority } from '@/types/integrations';

/** Query key factory */
export const ticketsKeys = {
  all: ['tickets'] as const,
  list: (filters?: { status?: TicketStatus; priority?: TicketPriority }) =>
    [...ticketsKeys.all, 'list', filters] as const,
  detail: (id: string) => [...ticketsKeys.all, 'detail', id] as const,
  counts: ['tickets', 'counts'] as const,
};

interface FetchTicketsParams {
  status?: TicketStatus;
  priority?: TicketPriority;
  limit?: number;
}

/**
 * Fetch FreeScout tickets
 */
async function fetchTickets(params?: FetchTicketsParams): Promise<FreeScoutTicket[]> {
  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.status) queryParams.status = params.status;
  if (params?.priority) queryParams.priority = params.priority;
  if (params?.limit) queryParams.pageSize = params.limit;

  const response = await api.get<{ conversations: FreeScoutTicket[] } | FreeScoutTicket[]>(
    '/integrations/freescout/tickets',
    { params: queryParams },
  );
  return Array.isArray(response) ? response : response.conversations;
}

/**
 * Fetch ticket by ID
 */
async function fetchTicketById(id: string): Promise<FreeScoutTicket | null> {
  return api.get<FreeScoutTicket>(`/integrations/freescout/tickets/${id}`);
}

/**
 * Update ticket status
 */
async function updateTicketStatus(params: {
  ticketId: string;
  status: TicketStatus;
}): Promise<void> {
  await api.post(`/integrations/freescout/tickets/${params.ticketId}/status`, {
    status: params.status,
  });
}

/**
 * Hook to fetch FreeScout tickets
 */
export function useTickets(params?: FetchTicketsParams) {
  return useQuery({
    queryKey: ticketsKeys.list(params),
    queryFn: () => fetchTickets(params),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to fetch open tickets
 */
export function useOpenTickets(limit?: number) {
  return useTickets({ status: 'open', limit });
}

/**
 * Hook to fetch a single ticket
 */
export function useTicket(id: string) {
  return useQuery({
    queryKey: ticketsKeys.detail(id),
    queryFn: () => fetchTicketById(id),
    staleTime: 30 * 1000,
    enabled: !!id,
  });
}

/**
 * Hook to get ticket counts by status
 */
export function useTicketCounts() {
  return useQuery({
    queryKey: ticketsKeys.counts,
    queryFn: async () => {
      const tickets = await fetchTickets();
      return {
        open: tickets.filter((t) => t.status === 'open').length,
        pending: tickets.filter((t) => t.status === 'pending').length,
        resolved: tickets.filter((t) => t.status === 'resolved').length,
        closed: tickets.filter((t) => t.status === 'closed').length,
        total: tickets.length,
        byPriority: {
          urgent: tickets.filter((t) => t.priority === 'urgent' && t.status === 'open').length,
          high: tickets.filter((t) => t.priority === 'high' && t.status === 'open').length,
          medium: tickets.filter((t) => t.priority === 'medium' && t.status === 'open').length,
          low: tickets.filter((t) => t.priority === 'low' && t.status === 'open').length,
        },
      };
    },
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to update ticket status
 */
export function useUpdateTicketStatus() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateTicketStatus,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ticketsKeys.all });
    },
  });
}
