import apiClient from '../../../shared/services/apiClient';

export interface Room {
  id: number;
  room_type_id: number;
  room_number: string;
  floor: number;
  status: 'available' | 'occupied' | 'maintenance';
  featured: boolean;
  price?: number;
  description?: string;
  capacity?: number;
  room_size?: string;
  view?: string;
  images?: string[];
  amenities?: string[];
  created_at: string;
  updated_at: string;
  room_type?: {
    id: number;
    name: string;
    description: string;
    base_price: number;
    capacity: number;
    amenities: string[];
    images: string[];
  };
  average_rating?: number | string | null;
  total_reviews?: number | string | null;
}

export interface RoomListResponse {
  success: boolean;
  status?: 'success' | 'error';
  data: {
    rooms: Room[];
    pagination?: {
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    };
  };
  message?: string;
}

export interface FeaturedRoomsParams {
  featured?: boolean;
  limit?: number;
}

export interface RoomSearchParams {
  type?: string;
  minPrice?: number;
  maxPrice?: number;
  capacity?: number;
  page?: number;
  limit?: number;
  sort?: string;
}

export const getFeaturedRooms = async (
  params: FeaturedRoomsParams = {}
): Promise<RoomListResponse> => {
  const response = await apiClient.get('/rooms', {
    params: {
      featured: params.featured ?? true,
      limit: params.limit ?? 6,
    },
  });
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || { rooms: [] },
    message: data.message,
  };
};

export const getRooms = async (
  params: RoomSearchParams = {},
  signal?: AbortSignal
): Promise<RoomListResponse> => {
  const response = await apiClient.get('/rooms', {
    params,
    signal,
  });
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  const isSuccess = data.status === 'success' || data.success === true;
  return {
    success: isSuccess,
    status: isSuccess ? 'success' : 'error',
    data: data.data || { rooms: [] },
    message: data.message,
  };
};

export const getRoomById = async (
  id: number
): Promise<{ success: boolean; data: { room: Room } }> => {
  const response = await apiClient.get(`/rooms/id/${id}`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || {},
  };
};

export const getRoomBookedDates = async (
  roomId: number
): Promise<{ success: boolean; data: { room_id: number; booked_dates: string[] } }> => {
  const response = await apiClient.get(`/rooms/${roomId}/booked-dates`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || { room_id: roomId, booked_dates: [] },
  };
};

export const getRoomByNumber = async (
  room_number: string
): Promise<{ success: boolean; data: { room: Room } }> => {
  const response = await apiClient.get(`/rooms/${room_number}`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || {},
  };
};

export interface AvailableSearchParams {
  from: string;
  to: string;
  type?: string;
  capacity?: number;
  page?: number;
  limit?: number;
}

export const searchAvailableRooms = async (
  params: AvailableSearchParams
): Promise<RoomListResponse> => {
  const response = await apiClient.get('/rooms/available', {
    params,
  });
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || { rooms: [] },
    message: data.message,
  };
};

export const getAmenities = async (): Promise<{
  success?: boolean;
  status?: string;
  data: { amenities: string[] };
}> => {
  const response = await apiClient.get('/rooms/amenities');
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    status: data.status,
    data: data.data || { amenities: [] },
  };
};

export const updateAmenity = async (
  oldName: string,
  newName: string
): Promise<{ success: boolean; message: string; data: { updated_count: number; old_name: string; new_name: string } }> => {
  const response = await apiClient.put(`/rooms/amenities/${encodeURIComponent(oldName)}`, {
    new_name: newName,
  });
  const responseData = response.data;
  return {
    success: responseData.status === 'success' || responseData.success === true,
    message: responseData.message || '',
    data: responseData.data || { updated_count: 0, old_name: oldName, new_name: newName },
  };
};

export const deleteAmenity = async (
  amenityName: string
): Promise<{ success: boolean; message: string; data: { updated_count: number; amenity_name: string } }> => {
  const response = await apiClient.delete(`/rooms/amenities/${encodeURIComponent(amenityName)}`);
  const data = response.data;
  return {
    success: data.status === 'success' || data.success === true,
    message: data.message || '',
    data: data.data || { updated_count: 0, amenity_name: amenityName },
  };
};

export interface RoomType {
  id: number;
  name: string;
  description?: string;
  base_price: number;
  capacity: number;
  amenities?: string[];
  created_at?: string;
  updated_at?: string;
}

export interface CreateRoomTypeData {
  name: string;
  description?: string;
  base_price: number;
  capacity: number;
  amenities?: string[];
}

export interface UpdateRoomTypeData {
  name?: string;
  description?: string;
  base_price?: number;
  capacity?: number;
  amenities?: string[];
}

export const getRoomTypes = async (): Promise<{
  success: boolean;
  status?: string;
  data: { room_types: RoomType[] };
}> => {
  const response = await apiClient.get('/rooms/room-types');
  const data = response.data;
  return {
    success: data.status === 'success' || data.success === true,
    status: data.status,
    data: data.data || { room_types: [] },
  };
};

export const getRoomType = async (id: number): Promise<{
  success: boolean;
  status?: string;
  data: { room_type: RoomType };
  message?: string;
}> => {
  const response = await apiClient.get(`/rooms/room-types/${id}`);
  const data = response.data;
  return {
    success: data.status === 'success' || data.success === true,
    status: data.status,
    data: data.data || {},
    message: data.message || '',
  };
};

export const createRoomType = async (
  data: CreateRoomTypeData
): Promise<{ success: boolean; data: { room_type: RoomType }; message: string }> => {
  const response = await apiClient.post('/rooms/room-types', data);
  const responseData = response.data;
  return {
    success: responseData.status === 'success' || responseData.success === true,
    data: responseData.data || {},
    message: responseData.message || '',
  };
};

export const updateRoomType = async (
  id: number,
  data: UpdateRoomTypeData
): Promise<{ success: boolean; data: { room_type: RoomType }; message: string }> => {
  const response = await apiClient.put(`/rooms/room-types/${id}`, data);
  const responseData = response.data;
  return {
    success: responseData.status === 'success' || responseData.success === true,
    data: responseData.data || {},
    message: responseData.message || '',
  };
};

export const deleteRoomType = async (
  id: number
): Promise<{ success: boolean; message: string }> => {
  const response = await apiClient.delete(`/rooms/room-types/${id}`);
  const data = response.data;
  return {
    success: data.status === 'success' || data.success === true,
    message: data.message || '',
  };
};

export interface CreateRoomData {
  room_number: string;
  floor: number;
  room_type_id: number;
  status: 'available' | 'occupied' | 'maintenance';
  featured?: boolean;
  price?: number;
  description?: string;
  capacity?: number;
  room_size?: string;
  view?: string;
  amenities?: string[];
}

export const createRoom = async (
  data: CreateRoomData
): Promise<{ success: boolean; data: { room: Room }; message: string }> => {
  const response = await apiClient.post('/rooms', data);
  const responseData = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: responseData.status === 'success' || responseData.success === true,
    data: responseData.data || {},
    message: responseData.message || '',
  };
};

export const updateRoom = async (
  id: number,
  data: Partial<CreateRoomData>
): Promise<{ success: boolean; data: { room: Room }; message: string }> => {
  const response = await apiClient.put(`/rooms/${id}`, data);
  const responseData = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: responseData.status === 'success' || responseData.success === true,
    data: responseData.data || {},
    message: responseData.message || '',
  };
};

export const deleteRoom = async (
  id: number
): Promise<{ success: boolean; message: string }> => {
  const response = await apiClient.delete(`/rooms/${id}`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    message: data.message || '',
  };
};

export const bulkDeleteRooms = async (
  ids: number[]
): Promise<{ success: boolean; message: string; data: { deleted_count: number; deleted_ids: number[] } }> => {
  const response = await apiClient.post('/rooms/bulk-delete', { ids });
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    message: data.message || '',
    data: data.data || { deleted_count: 0, deleted_ids: [] },
  };
};

export default {
  getFeaturedRooms,
  getRooms,
  getRoomById,
  getRoomByNumber,
  searchAvailableRooms,
  getAmenities,
  updateAmenity,
  deleteAmenity,
  getRoomTypes,
  getRoomType,
  createRoomType,
  updateRoomType,
  deleteRoomType,
  createRoom,
  updateRoom,
  deleteRoom,
  bulkDeleteRooms,
};
