import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTenant } from '@/contexts/tenant-context';
import { apiClient } from '@/lib/api';

export interface TaskListDto {
  items: TaskListItemDto[];
  total: number;
  page: number;
  pageSize: number;
}

export interface TaskListItemDto {
  id: string;
  title: string;
  status: string;
  assigneeId: string | null;
  assigneeName?: string;
  createdAt: string;
  isAssignedToMe: boolean;
}

export interface TaskDetailDto {
  id: string;
  title: string;
  description: string | null;
  status: string;
  assigneeId: string | null;
  assigneeName?: string;
  createdById: string;
  createdByName?: string;
  clubId: string;
  dueDate: string | null;
  createdAt: string;
  updatedAt: string;
  isAssignedToMe: boolean;
}

export interface CreateTaskRequest {
  title: string;
  description?: string;
  clubId: string;
  assigneeId?: string;
  dueDate?: string;
}

export interface UpdateTaskRequest {
  title?: string;
  description?: string;
  status?: string;
  assigneeId?: string;
  dueDate?: string;
}

export function useTasks(filters?: { status?: string; page?: number }) {
  const { activeClubId } = useTenant();

  return useQuery<TaskListDto>({
    queryKey: ['tasks', activeClubId, filters],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (filters?.status) params.append('status', filters.status);
      if (filters?.page) params.append('page', filters.page.toString());
      
      const res = await apiClient(`/api/tasks?${params}`);
      if (!res.ok) throw new Error('Failed to fetch tasks');
      return res.json();
    },
    enabled: !!activeClubId,
  });
}

export function useTask(id: string) {
  const { activeClubId } = useTenant();

  return useQuery<TaskDetailDto>({
    queryKey: ['tasks', activeClubId, id],
    queryFn: async () => {
      const res = await apiClient(`/api/tasks/${id}`);
      if (!res.ok) throw new Error('Failed to fetch task');
      return res.json();
    },
    enabled: !!activeClubId && !!id,
  });
}

export function useCreateTask() {
  const queryClient = useQueryClient();
  const { activeClubId } = useTenant();
  
  return useMutation({
    mutationFn: async (data: Omit<CreateTaskRequest, 'clubId'>) => {
      const payload: CreateTaskRequest = {
        ...data,
        clubId: activeClubId!,
      };
      const res = await apiClient('/api/tasks', {
        method: 'POST',
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error('Failed to create task');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId] });
    },
  });
}

export function useUpdateTask() {
  const queryClient = useQueryClient();
  const { activeClubId } = useTenant();
  
  return useMutation({
    mutationFn: async ({ id, data }: { id: string; data: UpdateTaskRequest }) => {
      const res = await apiClient(`/api/tasks/${id}`, {
        method: 'PATCH',
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error('Failed to update task');
      return res.json();
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId] });
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId, variables.id] });
    },
  });
}

export function useAssignTask() {
  const queryClient = useQueryClient();
  const { activeClubId } = useTenant();
  
  return useMutation({
    mutationFn: async (id: string) => {
      const res = await apiClient(`/api/tasks/${id}/assign`, {
        method: 'POST',
      });
      if (!res.ok) throw new Error('Failed to assign task');
      return res;
    },
    onSuccess: (_, id) => {
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId] });
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId, id] });
    },
  });
}

export function useUnassignTask() {
  const queryClient = useQueryClient();
  const { activeClubId } = useTenant();
  
  return useMutation({
    mutationFn: async (id: string) => {
      const res = await apiClient(`/api/tasks/${id}/assign`, {
        method: 'DELETE',
      });
      if (!res.ok) throw new Error('Failed to unassign task');
      return res;
    },
    onSuccess: (_, id) => {
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId] });
      queryClient.invalidateQueries({ queryKey: ['tasks', activeClubId, id] });
    },
  });
}
