/**
 * Service Management Hooks
 */

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

/**
 * Hook to fetch all services for current business
 */
export const useServices = () => {
  return useQuery<Service[]>({
    queryKey: ['services'],
    queryFn: async () => {
      const { data } = await apiClient.get('/services/');

      // Transform backend format to frontend format
      return data.map((s: any) => ({
        id: String(s.id),
        name: s.name,
        durationMinutes: s.duration || s.duration_minutes,
        price: parseFloat(s.price),
        price_cents: s.price_cents ?? Math.round(parseFloat(s.price) * 100),
        description: s.description || '',
        displayOrder: s.display_order ?? 0,
        photos: s.photos || [],
        is_active: s.is_active ?? true,
        created_at: s.created_at,
        is_archived_by_quota: s.is_archived_by_quota ?? false,
        // Pricing fields
        variable_pricing: s.variable_pricing ?? false,
        deposit_amount: s.deposit_amount ? parseFloat(s.deposit_amount) : null,
        deposit_amount_cents: s.deposit_amount_cents ?? (s.deposit_amount ? Math.round(parseFloat(s.deposit_amount) * 100) : null),
        deposit_percent: s.deposit_percent ? parseFloat(s.deposit_percent) : null,
        requires_deposit: s.requires_deposit ?? false,
        requires_saved_payment_method: s.requires_saved_payment_method ?? false,
        deposit_display: s.deposit_display || null,
        // Resource assignment
        all_resources: s.all_resources ?? true,
        resource_ids: (s.resource_ids || []).map((id: number) => String(id)),
        resource_names: s.resource_names || [],
      }));
    },
    retry: false, // Don't retry on 404 - endpoint may not exist yet
  });
};

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

      return {
        id: String(data.id),
        name: data.name,
        durationMinutes: data.duration || data.duration_minutes,
        price: parseFloat(data.price),
        description: data.description || '',
        displayOrder: data.display_order ?? 0,
        photos: data.photos || [],
      };
    },
    enabled: !!id,
    retry: false,
  });
};

// Input type for creating/updating services (not all Service fields required)
interface ServiceInput {
  name: string;
  durationMinutes: number;
  price?: number; // Price in dollars
  price_cents?: number; // Price in cents (preferred)
  description?: string;
  photos?: string[];
  variable_pricing?: boolean;
  deposit_amount?: number | null; // Deposit in dollars
  deposit_amount_cents?: number | null; // Deposit in cents (preferred)
  deposit_percent?: number | null;
  // Resource assignment (not yet implemented in backend)
  all_resources?: boolean;
  resource_ids?: string[];
  // Buffer times (not yet implemented in backend)
  prep_time?: number;
  takedown_time?: number;
  // Notification settings (not yet implemented in backend)
  reminder_enabled?: boolean;
  reminder_hours_before?: number;
  reminder_email?: boolean;
  reminder_sms?: boolean;
  thank_you_email_enabled?: boolean;
}

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

  return useMutation({
    mutationFn: async (serviceData: ServiceInput) => {
      // Convert price: prefer cents, fall back to dollars
      const priceInDollars = serviceData.price_cents !== undefined
        ? (serviceData.price_cents / 100).toString()
        : (serviceData.price ?? 0).toString();

      const backendData: Record<string, any> = {
        name: serviceData.name,
        duration: serviceData.durationMinutes,
        price: priceInDollars,
        description: serviceData.description || '',
        photos: serviceData.photos || [],
      };

      // Add pricing fields
      if (serviceData.variable_pricing !== undefined) {
        backendData.variable_pricing = serviceData.variable_pricing;
      }

      // Convert deposit: prefer cents, fall back to dollars
      if (serviceData.deposit_amount_cents !== undefined) {
        backendData.deposit_amount = serviceData.deposit_amount_cents !== null
          ? serviceData.deposit_amount_cents / 100
          : null;
      } else if (serviceData.deposit_amount !== undefined) {
        backendData.deposit_amount = serviceData.deposit_amount;
      }

      if (serviceData.deposit_percent !== undefined) {
        backendData.deposit_percent = serviceData.deposit_percent;
      }

      // Resource assignment
      if (serviceData.all_resources !== undefined) {
        backendData.all_resources = serviceData.all_resources;
      }
      if (serviceData.resource_ids !== undefined) {
        // Convert string IDs to numbers for the backend
        backendData.resource_ids = serviceData.resource_ids.map(id => parseInt(id, 10));
      }

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

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

  return useMutation({
    mutationFn: async ({ id, updates }: { id: string; updates: Partial<ServiceInput> }) => {
      const backendData: Record<string, any> = {};
      if (updates.name) backendData.name = updates.name;
      if (updates.durationMinutes) backendData.duration = updates.durationMinutes;

      // Convert price: prefer cents, fall back to dollars
      if (updates.price_cents !== undefined) {
        backendData.price = (updates.price_cents / 100).toString();
      } else if (updates.price !== undefined) {
        backendData.price = updates.price.toString();
      }

      if (updates.description !== undefined) backendData.description = updates.description;
      if (updates.photos !== undefined) backendData.photos = updates.photos;

      // Pricing fields
      if (updates.variable_pricing !== undefined) backendData.variable_pricing = updates.variable_pricing;

      // Convert deposit: prefer cents, fall back to dollars
      if (updates.deposit_amount_cents !== undefined) {
        backendData.deposit_amount = updates.deposit_amount_cents !== null
          ? updates.deposit_amount_cents / 100
          : null;
      } else if (updates.deposit_amount !== undefined) {
        backendData.deposit_amount = updates.deposit_amount;
      }

      if (updates.deposit_percent !== undefined) backendData.deposit_percent = updates.deposit_percent;

      // Resource assignment
      if (updates.all_resources !== undefined) backendData.all_resources = updates.all_resources;
      if (updates.resource_ids !== undefined) {
        // Convert string IDs to numbers for the backend
        backendData.resource_ids = updates.resource_ids.map(id => parseInt(id, 10));
      }

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

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

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

/**
 * Hook to reorder services (drag and drop)
 */
export const useReorderServices = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (orderedIds: string[]) => {
      // Convert string IDs to numbers for the backend
      const order = orderedIds.map(id => parseInt(id, 10));
      const { data } = await apiClient.post('/services/reorder/', { order });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['services'] });
    },
  });
};
