"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 { CreateTaskRequest, UpdateTaskRequest, CreateCompletionRequest, TaskResponse } from '@/lib/api/tasks';

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

export function useTasks() {
  const { tasks } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('tasks'),
    queryFn: () => tasks.list(),
  });
}

export function useTasksByResidence(residenceId: number) {
  const { tasks } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('tasks', 'by-residence', residenceId),
    queryFn: () => tasks.getByResidence(residenceId),
    enabled: !!residenceId,
  });
}

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

export function useKanbanBoard(residenceId: number) {
  const { tasks } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('tasks', 'kanban', residenceId),
    queryFn: () => tasks.getByResidence(residenceId),
    enabled: !!residenceId,
  });
}

export function useTaskCompletions(taskId: number) {
  const { tasks } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('tasks', taskId, 'completions'),
    queryFn: () => tasks.getCompletions(taskId),
    enabled: !!taskId,
  });
}

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

export function useCreateTask() {
  const queryClient = useQueryClient();
  const { tasks } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: CreateTaskRequest) => tasks.create(data),
    onSuccess: (result: TaskResponse) => {
      trackEvent(AnalyticsEvents.TASK_CREATED, {
        residence_id: result.residence_id,
        platform: 'web',
      });
      queryClient.invalidateQueries({ queryKey: qk('tasks') });
      queryClient.invalidateQueries({ queryKey: qk('residences') });
    },
  });
}

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

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

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

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

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

export function useCreateCompletion() {
  const queryClient = useQueryClient();
  const { tasks } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: ({
      data,
      images,
    }: {
      data: CreateCompletionRequest;
      images: File[];
    }) => {
      if (images.length > 0) {
        return tasks.createCompletionWithImages(
          {
            task_id: data.task_id,
            notes: data.notes,
            actual_cost: data.actual_cost,
            completed_at: data.completed_at,
          },
          images,
        );
      }
      return tasks.createCompletion(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('tasks') });
      queryClient.invalidateQueries({ queryKey: qk('residences') });
    },
  });
}
