/**
 * Resource Management Hooks
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '../api/client';
import { Resource, ResourceType } from '../types';

interface ResourceFilters {
  type?: ResourceType;
}

/**
 * Hook to fetch resources with optional type filter
 */
export const useResources = (filters?: ResourceFilters) => {
  return useQuery<Resource[]>({
    queryKey: ['resources', filters],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (filters?.type) params.append('type', filters.type);

      const { data } = await apiClient.get(`/resources/?${params}`);

      // Transform backend format to frontend format
      return data.map((r: any) => ({
        id: String(r.id),
        name: r.name,
        type: r.type as ResourceType,
        userId: r.user_id ? String(r.user_id) : undefined,
        maxConcurrentEvents: r.max_concurrent_events ?? 1,
        savedLaneCount: r.saved_lane_count,
        userCanEditSchedule: r.user_can_edit_schedule ?? false,
        // Location fields
        locationId: r.location ?? null,
        locationName: r.location_name ?? null,
        isMobile: r.is_mobile ?? false,
      }));
    },
  });
};

/**
 * Hook to get a single resource
 */
export const useResource = (id: string) => {
  return useQuery<Resource>({
    queryKey: ['resources', id],
    queryFn: async () => {
      const { data } = await apiClient.get(`/resources/${id}/`);

      return {
        id: String(data.id),
        name: data.name,
        type: data.type as ResourceType,
        userId: data.user_id ? String(data.user_id) : undefined,
        maxConcurrentEvents: data.max_concurrent_events ?? 1,
        savedLaneCount: data.saved_lane_count,
        userCanEditSchedule: data.user_can_edit_schedule ?? false,
        // Location fields
        locationId: data.location ?? null,
        locationName: data.location_name ?? null,
        isMobile: data.is_mobile ?? false,
      };
    },
    enabled: !!id,
  });
};

/**
 * Hook to create a resource
 */
export const useCreateResource = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (resourceData: Omit<Resource, 'id'>) => {
      const backendData: any = {
        name: resourceData.name,
        type: resourceData.type,
        user_id: resourceData.userId ? parseInt(resourceData.userId) : null,
      };

      if (resourceData.maxConcurrentEvents !== undefined) {
        backendData.max_concurrent_events = resourceData.maxConcurrentEvents;
      }
      if (resourceData.savedLaneCount !== undefined) {
        backendData.saved_lane_count = resourceData.savedLaneCount;
      }
      if (resourceData.userCanEditSchedule !== undefined) {
        backendData.user_can_edit_schedule = resourceData.userCanEditSchedule;
      }
      // Location fields
      if (resourceData.locationId !== undefined) {
        backendData.location = resourceData.locationId;
      }
      if (resourceData.isMobile !== undefined) {
        backendData.is_mobile = resourceData.isMobile;
      }

      const { data } = await apiClient.post('/resources/', backendData);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resources'] });
    },
  });
};

/**
 * Hook to update a resource
 */
export const useUpdateResource = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, updates }: { id: string; updates: Partial<Resource> }) => {
      const backendData: any = {};
      if (updates.name) backendData.name = updates.name;
      if (updates.type) backendData.type = updates.type;
      if (updates.userId !== undefined) {
        backendData.user = updates.userId ? parseInt(updates.userId) : null;
      }
      if (updates.maxConcurrentEvents !== undefined) {
        backendData.max_concurrent_events = updates.maxConcurrentEvents;
      }
      if (updates.savedLaneCount !== undefined) {
        backendData.saved_lane_count = updates.savedLaneCount;
      }
      if (updates.userCanEditSchedule !== undefined) {
        backendData.user_can_edit_schedule = updates.userCanEditSchedule;
      }
      // Location fields
      if (updates.locationId !== undefined) {
        backendData.location = updates.locationId;
      }
      if (updates.isMobile !== undefined) {
        backendData.is_mobile = updates.isMobile;
      }

      const { data } = await apiClient.patch(`/resources/${id}/`, backendData);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resources'] });
    },
  });
};

/**
 * Hook to delete a resource
 */
export const useDeleteResource = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      await apiClient.delete(`/resources/${id}/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resources'] });
    },
  });
};
