const API_BASE_URL = 'https://karibeo.lesoluciones.net:8443/api';

export interface TourismOffer {
  id: string;
  name: string;
  description: string;
  type: 'tour' | 'activity' | 'experience' | 'package';
  price: number;
  currency: string;
  duration: string;
  location: string;
  images: string[];
  availability: boolean;
  rating: number;
  reviewCount: number;
  includes: string[];
  excludes: string[];
  schedule: string;
  maxParticipants: number;
  minParticipants: number;
  category: string;
  tags: string[];
  createdAt: string;
}

export interface TourismCategory {
  id: string;
  name: string;
  description: string;
  icon: string;
  offerCount: number;
}

export interface TourBooking {
  id: string;
  offerId: string;
  offerName: string;
  date: string;
  participants: number;
  totalPrice: number;
  status: 'pending' | 'confirmed' | 'cancelled' | 'completed';
  customerInfo: {
    name: string;
    email: string;
    phone: string;
  };
}

class TourismService {
  private async getAuthToken(): Promise<string | null> {
    // Get token from localStorage or your preferred auth method
    return localStorage.getItem('auth_token');
  }

  async getTourismOffers(filters?: {
    type?: string;
    category?: string;
    minPrice?: number;
    maxPrice?: number;
    location?: string;
  }): Promise<TourismOffer[]> {
    const token = await this.getAuthToken();
    const params = new URLSearchParams();
    
    if (filters) {
      if (filters.type) params.append('type', filters.type);
      if (filters.category) params.append('category', filters.category);
      if (filters.minPrice) params.append('min_price', filters.minPrice.toString());
      if (filters.maxPrice) params.append('max_price', filters.maxPrice.toString());
      if (filters.location) params.append('location', filters.location);
    }

    const response = await fetch(`${API_BASE_URL}/tourism/offers?${params}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to fetch tourism offers');
    }

    return await response.json();
  }

  async getTourismOffer(offerId: string): Promise<TourismOffer> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/tourism/offers/${offerId}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to fetch tourism offer');
    }

    return await response.json();
  }

  async createTourismOffer(data: Partial<TourismOffer>): Promise<TourismOffer> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/tourism/offers`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error('Failed to create tourism offer');
    }

    return await response.json();
  }

  async updateTourismOffer(offerId: string, data: Partial<TourismOffer>): Promise<TourismOffer> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/tourism/offers/${offerId}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error('Failed to update tourism offer');
    }

    return await response.json();
  }

  async deleteTourismOffer(offerId: string): Promise<void> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/tourism/offers/${offerId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to delete tourism offer');
    }
  }

  async getCategories(): Promise<TourismCategory[]> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/tourism/categories`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to fetch categories');
    }

    return await response.json();
  }

  async createTourBooking(data: {
    offerId: string;
    date: string;
    participants: number;
    customerInfo: {
      name: string;
      email: string;
      phone: string;
    };
  }): Promise<TourBooking> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/tourism/bookings`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error('Failed to create booking');
    }

    return await response.json();
  }

  async getTourBookings(status?: string): Promise<TourBooking[]> {
    const token = await this.getAuthToken();
    const url = status 
      ? `${API_BASE_URL}/tourism/bookings?status=${status}`
      : `${API_BASE_URL}/tourism/bookings`;

    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to fetch bookings');
    }

    return await response.json();
  }
}

export const tourismService = new TourismService();
