import { useQuery, useMutation, useQueryClient, type UseQueryResult, type UseMutationResult } from '@tanstack/react-query';

import {
  fetchAlbums,
  fetchPhotos,
  fetchPhotosByAlbum,
  type PhotoFilters,
} from '@/api/photos';
import {
  fetchIdentities,
  fetchIdentityPhotos,
  mergeIdentities,
  renameIdentity,
} from '@/api/identities';
import type { Album, Identity, IdentityPhotoListItem, Photo } from '@/types';

import { STALE_TIME } from './refreshConfig';

export function usePhotos(filters: PhotoFilters = {}): UseQueryResult<Photo[]> {
  return useQuery({
    queryKey: ['photos', filters],
    queryFn: () => fetchPhotos(filters),
    staleTime: STALE_TIME,
  });
}

export function useAlbums(deviceId: string | undefined): UseQueryResult<Album[]> {
  return useQuery({
    queryKey: ['albums', deviceId],
    queryFn: () => (deviceId ? fetchAlbums(deviceId) : Promise.resolve([] as Album[])),
    enabled: Boolean(deviceId),
    staleTime: STALE_TIME,
  });
}

export function useAlbumPhotos(albumId: string | undefined, limit = 200): UseQueryResult<Photo[]> {
  return useQuery({
    queryKey: ['album-photos', albumId, limit],
    queryFn: () => (albumId ? fetchPhotosByAlbum(albumId, limit) : Promise.resolve([] as Photo[])),
    enabled: Boolean(albumId),
    staleTime: STALE_TIME,
  });
}

export function useIdentities(deviceId: string | undefined): UseQueryResult<Identity[]> {
  return useQuery({
    queryKey: ['identities', deviceId],
    queryFn: () => (deviceId ? fetchIdentities(deviceId) : Promise.resolve([] as Identity[])),
    enabled: Boolean(deviceId),
    staleTime: STALE_TIME,
  });
}

export function useIdentityPhotos(identityId: string | undefined, limit = 100): UseQueryResult<IdentityPhotoListItem[]> {
  return useQuery({
    queryKey: ['identity-photos', identityId, limit],
    queryFn: () => (identityId ? fetchIdentityPhotos(identityId, limit) : Promise.resolve([] as IdentityPhotoListItem[])),
    enabled: Boolean(identityId),
    staleTime: STALE_TIME,
  });
}

export function useRenameIdentity(): UseMutationResult<void, Error, { id: string; name: string | null }> {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, name }) => renameIdentity(id, name),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['identities'] });
    },
  });
}

export function useMergeIdentities(): UseMutationResult<void, Error, { targetId: string; sourceId: string }> {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ targetId, sourceId }) => mergeIdentities(targetId, sourceId),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['identities'] });
      void qc.invalidateQueries({ queryKey: ['identity-photos'] });
    },
  });
}
