import apiClient from '../../../shared/services/apiClient';
import type { Booking } from './bookingService';

export interface RoomBlock {
  room_type_id: number;
  num_rooms: number;
  rate_per_room: number;
}

export interface GroupBookingData {
  coordinator_name?: string;
  coordinator_email?: string;
  coordinator_phone?: string;
  check_in_date: string;
  check_out_date: string;
  room_blocks: RoomBlock[];
  group_name?: string;
  group_type?: string;
  payment_option?: 'coordinator_pays_all' | 'individual_payments' | 'split_payment';
  deposit_required?: boolean;
  deposit_percentage?: number;
  special_requests?: string;
  notes?: string;
  cancellation_policy?: string;
  cancellation_deadline?: string;
  cancellation_penalty_percentage?: number;
  group_discount_percentage?: number;
}

export interface GroupBookingMemberData {
  full_name: string;
  email?: string;
  phone?: string;
  user_id?: number;
  room_block_id?: number;
  special_requests?: string;
  preferences?: Record<string, unknown>;
}

export interface GroupPaymentData {
  amount: number;
  payment_method: string;
  payment_type?: 'deposit' | 'full' | 'remaining';
  transaction_id?: string;
  paid_by_member_id?: number;
  paid_by_user_id?: number;
  notes?: string;
}

export interface GroupBooking {
  id: number;
  group_booking_number: string;
  coordinator: {
    id: number;
    name: string;
    email: string;
    phone?: string;
  };
  group_name?: string;
  group_type?: string;
  total_rooms: number;
  total_guests: number;
  check_in_date: string;
  check_out_date: string;
  base_rate_per_room: number;
  group_discount_percentage: number;
  group_discount_amount: number;
  original_total_price: number;
  discount_amount: number;
  total_price: number;
  payment_option: 'coordinator_pays_all' | 'individual_payments' | 'split_payment';
  deposit_required: boolean;
  deposit_percentage?: number;
  deposit_amount?: number;
  amount_paid: number;
  balance_due: number;
  status: 'draft' | 'pending' | 'confirmed' | 'partially_confirmed' | 'checked_in' | 'checked_out' | 'cancelled';
  special_requests?: string;
  notes?: string;
  cancellation_policy?: string;
  cancellation_deadline?: string;
  cancellation_penalty_percentage?: number;
  created_at: string;
  updated_at: string;
  confirmed_at?: string;
  cancelled_at?: string;
  room_blocks?: RoomBlockDetail[];
  members?: GroupBookingMember[];
  payments?: GroupPayment[];
}

export interface RoomBlockDetail {
  id: number;
  room_type_id: number;
  room_type?: {
    id: number;
    name: string;
    base_price: number;
  };
  rooms_blocked: number;
  rooms_confirmed: number;
  rooms_available: number;
  rate_per_room: number;
  total_block_price: number;
  is_active: boolean;
  block_released_at?: string;
}

export interface GroupBookingMember {
  id: number;
  full_name: string;
  email?: string;
  phone?: string;
  user_id?: number;
  room_block_id?: number;
  assigned_room_id?: number;
  individual_booking_id?: number;
  special_requests?: string;
  preferences?: Record<string, unknown>;
  individual_amount?: number;
  individual_paid: number;
  individual_balance: number;
  is_checked_in: boolean;
  checked_in_at?: string;
  is_checked_out: boolean;
  checked_out_at?: string;
}

export interface GroupPayment {
  id: number;
  amount: number;
  payment_method: string;
  payment_type: string;
  payment_status: string;
  transaction_id?: string;
  payment_date?: string;
  notes?: string;
  paid_by_member_id?: number;
  paid_by_user_id?: number;
  created_at: string;
}

export interface GroupBookingListResponse {
  status: string;
  data: {
    group_bookings: GroupBooking[];
    pagination?: {
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    };
  };
}

export interface GroupBookingResponse {
  status: string;
  message?: string;
  data: {
    group_booking: GroupBooking;
  };
}

export interface GroupBookingMemberResponse {
  status: string;
  message?: string;
  data: {
    member: GroupBookingMember;
  };
}

export interface GroupPaymentResponse {
  status: string;
  message?: string;
  data: {
    payment: GroupPayment;
  };
}

const groupBookingService = {
  // Create a new group booking
  async createGroupBooking(data: GroupBookingData): Promise<GroupBookingResponse> {
    const response = await apiClient.post('/group-bookings', data);
    return response.data;
  },

  // Get all group bookings (admin/staff)
  async getGroupBookings(params?: {
    search?: string;
    status?: string;
    page?: number;
    limit?: number;
  }): Promise<GroupBookingListResponse> {
    const response = await apiClient.get('/group-bookings', { params });
    return response.data;
  },

  // Get current user's group bookings
  async getMyGroupBookings(): Promise<GroupBookingListResponse> {
    const response = await apiClient.get('/group-bookings/me');
    return response.data;
  },

  // Get a specific group booking
  async getGroupBooking(groupBookingId: number): Promise<GroupBookingResponse> {
    const response = await apiClient.get(`/group-bookings/${groupBookingId}`);
    return response.data;
  },

  // Add a member to a group booking
  async addMember(
    groupBookingId: number,
    memberData: GroupBookingMemberData
  ): Promise<GroupBookingMemberResponse> {
    const response = await apiClient.post(
      `/group-bookings/${groupBookingId}/members`,
      memberData
    );
    return response.data;
  },

  // Confirm a group booking
  async confirmGroupBooking(groupBookingId: number): Promise<GroupBookingResponse> {
    const response = await apiClient.post(`/group-bookings/${groupBookingId}/confirm`);
    return response.data;
  },

  // Assign a room to a member and create individual booking
  async assignRoomToMember(
    groupBookingId: number,
    memberId: number,
    roomId: number
  ): Promise<{ status: string; message?: string; data: { booking: Booking } }> {
    const response = await apiClient.post(
      `/group-bookings/${groupBookingId}/members/${memberId}/assign-room`,
      { room_id: roomId }
    );
    return response.data;
  },

  // Add a payment to a group booking
  async addPayment(
    groupBookingId: number,
    paymentData: GroupPaymentData
  ): Promise<GroupPaymentResponse> {
    const response = await apiClient.post(
      `/group-bookings/${groupBookingId}/payments`,
      paymentData
    );
    return response.data;
  },

  // Cancel a group booking
  async cancelGroupBooking(
    groupBookingId: number,
    reason?: string
  ): Promise<GroupBookingResponse> {
    const response = await apiClient.post(`/group-bookings/${groupBookingId}/cancel`, {
      reason,
    });
    return response.data;
  },

  // Check availability for a group booking
  async checkAvailability(groupBookingId: number): Promise<{
    status: string;
    data: {
      availability: Array<{
        room_block_id: number;
        room_type_id: number;
        rooms_blocked: number;
        availability: {
          available: boolean;
          available_count: number;
          required_count: number;
          message?: string;
        };
      }>;
    };
  }> {
    const response = await apiClient.get(`/group-bookings/${groupBookingId}/availability`);
    return response.data;
  },
};

export default groupBookingService;

