import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  tenantsApi,
  TenantQueryParams,
  TenantDto,
  PaginatedTenants,
  GlobalStats,
  CreateTenantDto,
  UpdateTenantDto,
  TenantAdminDto,
  CreateTenantAdminDto,
} from '../infrastructure/tenants.api';

// Query keys
export const TENANT_KEYS = {
  all: ['tenants'] as const,
  stats: ['tenants', 'stats'] as const,
  list: (params: TenantQueryParams) => ['tenants', 'list', params] as const,
  detail: (id: string) => ['tenants', 'detail', id] as const,
  admins: (tenantId: string) => ['tenants', 'admins', tenantId] as const,
};

// Global statistics query
export function useTenantStats() {
  return useQuery<GlobalStats>({
    queryKey: TENANT_KEYS.stats,
    queryFn: () => tenantsApi.getGlobalStats(),
    refetchInterval: 60000, // Refresh every minute
  });
}

// Tenant list query
export function useTenants(params: TenantQueryParams) {
  return useQuery<PaginatedTenants>({
    queryKey: TENANT_KEYS.list(params),
    queryFn: () => tenantsApi.listTenants(params),
  });
}

// Tenant detail query
export function useTenantDetail(id: string, enabled = true) {
  return useQuery<TenantDto>({
    queryKey: TENANT_KEYS.detail(id),
    queryFn: () => tenantsApi.getTenantDetail(id),
    enabled: enabled && !!id,
  });
}

// Tenant admins query
export function useTenantAdmins(tenantId: string, enabled = true) {
  return useQuery<TenantAdminDto[]>({
    queryKey: TENANT_KEYS.admins(tenantId),
    queryFn: () => tenantsApi.getTenantAdmins(tenantId),
    enabled: enabled && !!tenantId,
  });
}

// Create tenant mutation
export function useCreateTenant() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (dto: CreateTenantDto) => tenantsApi.createTenant(dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.all });
    },
  });
}

// Update tenant mutation
export function useUpdateTenant() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateTenantDto }) =>
      tenantsApi.updateTenant(id, dto),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.all });
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.detail(id) });
    },
  });
}

// Suspend tenant mutation
export function useSuspendTenant() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, reason }: { id: string; reason?: string }) =>
      tenantsApi.suspendTenant(id, reason),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.all });
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.detail(id) });
    },
  });
}

// Activate tenant mutation
export function useActivateTenant() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => tenantsApi.activateTenant(id),
    onSuccess: (_, id) => {
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.all });
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.detail(id) });
    },
  });
}

// Archive tenant mutation
export function useArchiveTenant() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => tenantsApi.archiveTenant(id),
    onSuccess: (_, id) => {
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.all });
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.detail(id) });
    },
  });
}

// Create tenant admin mutation
export function useCreateTenantAdmin() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ tenantId, dto }: { tenantId: string; dto: CreateTenantAdminDto }) =>
      tenantsApi.createTenantAdmin(tenantId, dto),
    onSuccess: (_, { tenantId }) => {
      queryClient.invalidateQueries({ queryKey: TENANT_KEYS.admins(tenantId) });
    },
  });
}

// Re-export types
export type {
  TenantDto,
  TenantStatus,
  TenantPlan,
  TenantConfigData,
  TenantAdminDto,
  PaginatedTenants,
  GlobalStats,
  TenantQueryParams,
  CreateTenantDto,
  UpdateTenantDto,
  CreateTenantAdminDto,
} from '../infrastructure/tenants.api';
