import { Property, MovingService, PropertyFilters, MovingServiceFilters, Booking } from '../types';

// Base API URL - Update this to match your backend URL
const API_BASE_URL = 'http://localhost:5000/api';

class ApiService {
  private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
    const url = `${API_BASE_URL}${endpoint}`;
    
    const defaultHeaders = {
      'Content-Type': 'application/json',
    };

    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          ...defaultHeaders,
          ...options.headers,
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error(`API request failed for ${endpoint}:`, error);
      throw error;
    }
  }

  // Property API methods
  async getProperties(filters: PropertyFilters = {}): Promise<Property[]> {
    const queryParams = new URLSearchParams();
    
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParams.append(key, value.toString());
      }
    });

    const endpoint = `/properties${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
    return this.request<Property[]>(endpoint);
  }

  async getProperty(id: string): Promise<Property> {
    return this.request<Property>(`/properties/${id}`);
  }

  async getPropertiesForMap(): Promise<Array<{
    id: string;
    title: string;
    price: string;
    type: string;
    latitude: string | null;
    longitude: string | null;
    image_url: string | null;
  }>> {
    return this.request(`/properties/map`);
  }

  // Moving Services API methods
  async getMovingServices(filters: MovingServiceFilters = {}): Promise<MovingService[]> {
    const queryParams = new URLSearchParams();
    
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParams.append(key, value.toString());
      }
    });

    const endpoint = `/moving-services${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
    return this.request<MovingService[]>(endpoint);
  }

  async getMovingService(id: string): Promise<MovingService> {
    return this.request<MovingService>(`/moving-services/${id}`);
  }

  async createBooking(bookingData: {
    serviceId: string;
    customerName: string;
    customerEmail: string;
    customerPhone: string;
    serviceDate: string;
    notes?: string;
  }): Promise<Booking> {
    return this.request<Booking>('/bookings', {
      method: 'POST',
      body: JSON.stringify(bookingData),
    });
  }

  async sendMessage(messageData: {
    propertyId?: string;
    serviceId?: string;
    senderName: string;
    senderEmail: string;
    senderPhone?: string;
    message: string;
  }): Promise<any> {
    return this.request('/messages', {
      method: 'POST',
      body: JSON.stringify(messageData),
    });
  }

  // Contact methods for mobile integration
  async sendContactInquiry(inquiryData: {
    name: string;
    email: string;
    phone?: string;
    subject: string;
    message: string;
  }): Promise<any> {
    return this.request('/contact', {
      method: 'POST',
      body: JSON.stringify(inquiryData),
    });
  }
}

export const apiService = new ApiService();