'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { IntegrationType, IntegrationConfig, IntegrationStatus } from '@/types/integrations';

/** API response shape from backend */
interface IntegrationStatusApiResponse {
  type: IntegrationType;
  name: string;
  configured: boolean;
  connected: boolean;
  lastChecked?: string;
  latencyMs?: number;
  error?: string;
  missingConfig?: string[];
}

interface IntegrationsOverviewApiResponse {
  integrations: IntegrationStatusApiResponse[];
  configuredCount: number;
  connectedCount: number;
  totalCount: number;
}

export interface TestConnectionResponse {
  type: string;
  success: boolean;
  healthy: boolean;
  message: string;
  latencyMs?: number;
  timestamp: string;
}

/** Map API status response to frontend IntegrationConfig */
function mapToConfig(item: IntegrationStatusApiResponse): IntegrationConfig {
  let status: IntegrationStatus = 'disconnected';
  if (item.connected) status = 'connected';
  else if (item.error) status = 'error';
  else if (!item.configured) status = 'configuring';

  return {
    id: item.type,
    type: item.type,
    name: item.name,
    enabled: item.configured,
    status,
    lastSync: item.lastChecked ? new Date(item.lastChecked) : undefined,
    lastError: item.error,
    syncInterval: 15,
    createdAt: new Date(),
    updatedAt: new Date(),
  };
}

/** Query key factory for integration queries */
export const integrationKeys = {
  all: ['integrations'] as const,
  status: (type: IntegrationType) => [...integrationKeys.all, 'status', type] as const,
  config: (type: IntegrationType) => [...integrationKeys.all, 'config', type] as const,
};

/**
 * Fetch integration status from API
 */
async function fetchIntegrationStatus(type: IntegrationType): Promise<IntegrationStatusApiResponse> {
  return api.get<IntegrationStatusApiResponse>(`/integrations/${type}/status`);
}

/**
 * Fetch all integration statuses
 */
async function fetchAllIntegrationStatuses(): Promise<IntegrationsOverviewApiResponse> {
  return api.get<IntegrationsOverviewApiResponse>('/integrations/status');
}

/**
 * Test connection to an integration
 */
async function testConnection(type: IntegrationType): Promise<TestConnectionResponse> {
  return api.post<TestConnectionResponse>(`/integrations/${type}/test-connection`);
}

/**
 * Hook to get the status of a specific integration
 */
export function useIntegrationStatus(type: IntegrationType) {
  return useQuery({
    queryKey: integrationKeys.status(type),
    queryFn: async () => {
      const response = await fetchIntegrationStatus(type);
      return mapToConfig(response);
    },
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to get all integration statuses
 */
export function useAllIntegrationStatuses() {
  return useQuery({
    queryKey: integrationKeys.all,
    queryFn: async () => {
      const response = await fetchAllIntegrationStatuses();
      return response.integrations.map(mapToConfig);
    },
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to test an integration connection
 */
export function useTestConnection() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: testConnection,
    onSuccess: (_, type) => {
      queryClient.invalidateQueries({ queryKey: integrationKeys.status(type) });
    },
  });
}

/**
 * Hook to trigger sync for an integration
 */
export function useTriggerSync() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (type: IntegrationType) =>
      api.post<{ success: boolean }>(`/integrations/${type}/test-connection`),
    onSuccess: (_, type) => {
      queryClient.invalidateQueries({ queryKey: integrationKeys.all });
    },
  });
}
