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

export interface PublicService {
  id: number;
  name: string;
  description: string;
  duration: number;
  price_cents: number;
  deposit_amount_cents: number | null;
  photos: string[] | null;
}

export interface PublicBusinessInfo {
  name: string;
  logo_url: string | null;
  primary_color: string;
  secondary_color: string | null;
  service_selection_heading: string;
  service_selection_subheading: string;
}

export const usePublicServices = () => {
  return useQuery<PublicService[]>({
    queryKey: ['publicServices'],
    queryFn: async () => {
      const response = await api.get('/public/services/');
      return response.data;
    },
    retry: false,
  });
};

export const usePublicBusinessInfo = () => {
  return useQuery<PublicBusinessInfo>({
    queryKey: ['publicBusinessInfo'],
    queryFn: async () => {
      const response = await api.get('/public/business/');
      return response.data;
    },
    retry: false,
  });
};

export interface AvailabilitySlot {
  time: string; // ISO datetime string
  display: string; // Human-readable time like "9:00 AM"
  available: boolean;
}

export interface AvailabilityResponse {
  date: string;
  service_id: number;
  is_open: boolean;
  business_hours?: {
    start: string;
    end: string;
  };
  slots: AvailabilitySlot[];
  business_timezone?: string;
  timezone_display_mode?: 'business' | 'viewer';
}

export interface BusinessHoursDay {
  date: string;
  is_open: boolean;
  hours: {
    start: string;
    end: string;
  } | null;
}

export interface BusinessHoursResponse {
  dates: BusinessHoursDay[];
}

export const usePublicAvailability = (serviceId: number | undefined, date: string | undefined) => {
  return useQuery<AvailabilityResponse>({
    queryKey: ['publicAvailability', serviceId, date],
    queryFn: async () => {
      const response = await api.get(`/public/availability/?service_id=${serviceId}&date=${date}`);
      return response.data;
    },
    enabled: !!serviceId && !!date,
  });
};

export const usePublicBusinessHours = (startDate: string | undefined, endDate: string | undefined) => {
  return useQuery<BusinessHoursResponse>({
    queryKey: ['publicBusinessHours', startDate, endDate],
    queryFn: async () => {
      const response = await api.get(`/public/business-hours/?start_date=${startDate}&end_date=${endDate}`);
      return response.data;
    },
    enabled: !!startDate && !!endDate,
  });
};

export const useCreateBooking = () => {
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.post('/public/bookings/', data);
      return response.data;
    },
  });
};
