import apiClient from './apiClient';

export type PackageStatus = 'active' | 'inactive' | 'scheduled' | 'expired';
export type PackageItemType = 'room' | 'service' | 'breakfast' | 'activity' | 'amenity' | 'discount';

export interface PackageItem {
  id?: number;
  item_type: PackageItemType;
  item_id?: number;
  item_name: string;
  item_description?: string;
  quantity: number;
  unit?: string;
  price?: number;
  included: boolean;
  price_modifier?: number;
  display_order: number;
  extra_data?: any;
}

export interface Package {
  id: number;
  name: string;
  code: string;
  description?: string;
  status: PackageStatus;
  base_price?: number;
  price_modifier: number;
  discount_percentage?: number;
  room_type_id?: number;
  room_type_name?: string;
  min_nights?: number;
  max_nights?: number;
  valid_from?: string;
  valid_to?: string;
  image_url?: string;
    highlights?: string[];
    terms_conditions?: string;
    extra_data?: any;
    items?: PackageItem[];
  created_at?: string;
  updated_at?: string;
}

export interface PackageListResponse {
  status: string;
  data: {
    packages: Package[];
    pagination?: {
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    };
  };
}

export interface CreatePackageData {
  name: string;
  code: string;
  description?: string;
  status?: PackageStatus;
  base_price?: number;
  price_modifier?: number;
  discount_percentage?: number;
  room_type_id?: number;
  min_nights?: number;
  max_nights?: number;
  valid_from?: string;
  valid_to?: string;
  image_url?: string;
  highlights?: string[];
  terms_conditions?: string;
  extra_data?: any;
  items?: PackageItem[];
}

export interface UpdatePackageData {
  name?: string;
  description?: string;
  status?: PackageStatus;
  base_price?: number;
  price_modifier?: number;
  discount_percentage?: number;
  room_type_id?: number;
  min_nights?: number;
  max_nights?: number;
  valid_from?: string;
  valid_to?: string;
  image_url?: string;
  highlights?: string[];
  terms_conditions?: string;
  extra_data?: any;
}

export interface GetAvailablePackagesParams {
  room_type_id: number;
  check_in: string;
  check_out: string;
  num_nights?: number;
}

class PackageService {
  async getPackages(params?: {
    search?: string;
    status?: string;
    room_type_id?: number;
    page?: number;
    limit?: number;
  }): Promise<PackageListResponse> {
    const response = await apiClient.get('/packages', { params });
    return response.data;
  }

  async getPackage(id: number): Promise<{ status: string; data: { package: Package } }> {
    const response = await apiClient.get(`/packages/${id}`);
    return response.data;
  }

  async createPackage(data: CreatePackageData): Promise<{ status: string; message: string; data: { package_id: number } }> {
    const response = await apiClient.post('/packages', data);
    return response.data;
  }

  async updatePackage(id: number, data: UpdatePackageData): Promise<{ status: string; message: string }> {
    const response = await apiClient.put(`/packages/${id}`, data);
    return response.data;
  }

  async deletePackage(id: number): Promise<{ status: string; message: string }> {
    const response = await apiClient.delete(`/packages/${id}`);
    return response.data;
  }

  async getAvailablePackages(params: GetAvailablePackagesParams): Promise<{ status: string; data: { packages: Package[] } }> {
    const response = await apiClient.get(`/packages/available/${params.room_type_id}`, {
      params: {
        check_in: params.check_in,
        check_out: params.check_out,
        num_nights: params.num_nights,
      },
    });
    return response.data;
  }

  /**
   * Calculate the total price for a package
   */
  calculatePackagePrice(
    baseRoomPrice: number,
    numNights: number,
    packageData: Package
  ): number {
    let totalPrice = 0;

    // If package has a fixed base price, use it
    if (packageData.base_price) {
      totalPrice = packageData.base_price * numNights;
    } else {
      // Calculate from room price and items
      totalPrice = baseRoomPrice * numNights;

      // Add item prices if not included
      if (packageData.items) {
        for (const item of packageData.items) {
          if (!item.included && item.price) {
            const itemPrice = item.price * item.quantity;
            totalPrice += itemPrice;
          }
        }
      }
    }

    // Apply price modifier
    if (packageData.price_modifier) {
      totalPrice = totalPrice * packageData.price_modifier;
    }

    // Apply discount
    if (packageData.discount_percentage) {
      totalPrice = totalPrice * (1 - packageData.discount_percentage / 100);
    }

    return Math.max(0, totalPrice);
  }
}

const packageService = new PackageService();
export default packageService;

