"use client";

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';
import { trackEvent, AnalyticsEvents } from '@/lib/analytics';

// ---------------------------------------------------------------------------
// Query hooks
// ---------------------------------------------------------------------------

export function useShareCode(residenceId: number) {
  const { sharing } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('residences', residenceId, 'share-code'),
    queryFn: () => sharing.getShareCode(residenceId),
    enabled: !!residenceId,
  });
}

export function useResidenceUsers(residenceId: number) {
  const { sharing } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('residences', residenceId, 'users'),
    queryFn: () => sharing.getResidenceUsers(residenceId),
    enabled: !!residenceId,
  });
}

// ---------------------------------------------------------------------------
// Mutation hooks
// ---------------------------------------------------------------------------

export function useGenerateShareCode(residenceId: number) {
  const queryClient = useQueryClient();
  const { sharing } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: () => sharing.generateShareCode(residenceId),
    onSuccess: () => {
      trackEvent(AnalyticsEvents.RESIDENCE_SHARED, { method: 'code', platform: 'web' });
      queryClient.invalidateQueries({ queryKey: qk('residences', residenceId, 'share-code') });
    },
  });
}

export function useRemoveResidenceUser(residenceId: number) {
  const queryClient = useQueryClient();
  const { sharing } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (userId: number) => sharing.removeUser(residenceId, userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('residences', residenceId, 'users') });
    },
  });
}

export function useJoinResidence() {
  const queryClient = useQueryClient();
  const { sharing } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (code: string) => sharing.joinWithCode({ code }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('residences') });
    },
  });
}
