"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';
import type { DocumentListParams, CreateDocumentRequest, UpdateDocumentRequest, DocumentResponse } from '@/lib/api/documents';

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

export function useDocuments(params?: DocumentListParams) {
  const { documents } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('documents', params),
    queryFn: () => documents.list(params),
    select: (data) => (Array.isArray(data) ? data : []),
  });
}

export function useWarranties() {
  const { documents } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('documents', 'warranties'),
    queryFn: () => documents.listWarranties(),
    select: (data) => (Array.isArray(data) ? data : []),
  });
}

export function useDocument(id: number) {
  const { documents } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({ queryKey: qk('documents', id), queryFn: () => documents.get(id), enabled: !!id });
}

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

export function useCreateDocument() {
  const queryClient = useQueryClient();
  const { documents } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: ({ data, file }: { data: CreateDocumentRequest; file?: File }) => {
      if (file) {
        return documents.createWithFile(data, file);
      }
      return documents.create(data);
    },
    onSuccess: (result: DocumentResponse) => {
      trackEvent(AnalyticsEvents.DOCUMENT_CREATED, {
        type: result.document_type,
        platform: 'web',
      });
      queryClient.invalidateQueries({ queryKey: qk('documents') });
    },
  });
}

export function useUpdateDocument(id: number) {
  const queryClient = useQueryClient();
  const { documents } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: UpdateDocumentRequest) =>
      documents.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('documents') });
      queryClient.invalidateQueries({ queryKey: qk('documents', id) });
    },
  });
}

export function useDeleteDocument() {
  const queryClient = useQueryClient();
  const { documents } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (id: number) => documents.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('documents') });
    },
  });
}
