import 'package:comwell_key_app/overview/models/booking.dart';
import 'package:comwell_key_app/services/models/booking_dto.dart';
import 'package:equatable/equatable.dart';

class MyBookingState extends Equatable {
  final Iterable<BookingAddonItem> _items;
  final Error? error;
  final bool isLoading;
  final Booking? booking;
  final bool applyClubPoints;
  final int clubPoints;
  final bool isTermsAccepted;
  final bool showTermsError;

  const MyBookingState({
    required this.booking,
    required Iterable<BookingAddonItem> items,
    this.error,
    required this.isLoading,
    required this.applyClubPoints,
    required this.clubPoints,
    required this.isTermsAccepted,
    required this.showTermsError,
  }) : _items = items;

  int get totalPriceBeforeDiscount => _sumOfList(_items);

  int get totalPriceAfterDiscount => _sumOfList(items);

  int get totalPrice => _sumOfList(items);

  Iterable<BookingAddonItem> get items {
    if (applyClubPoints) {
      return [
        ..._items,
        BookingAddonItem("discount", "discount", clubPoints * -1, clubPoints * -1),
      ];
    }

    return _items;
  }

  int _sumOfList(Iterable<BookingAddonItem> list) {
    if (list.isEmpty) return 0;
    return list.map((item) => item.price).reduce((total, price) => total + price);
  }

  MyBookingState.initial(Booking this.booking)
    : isTermsAccepted = false,
      error = null,
      isLoading = false,
      showTermsError = false,
      clubPoints = 0,
      applyClubPoints = false,
      _items = [];

  MyBookingState termsAccepted() => copyWith(isTermsAccepted: true, showTermsError: false);

  MyBookingState termsDenied() => copyWith(isTermsAccepted: false);

  MyBookingState clubPointsApplied() => copyWith(applyClubPoints: true);

  MyBookingState clubPointsRemoved() => copyWith(applyClubPoints: false);

  MyBookingState clubPointsFetched(int clubPoints) =>
      copyWith(clubPoints: clubPoints, items: _items);

  MyBookingState showAcceptTermsError() => copyWith(showTermsError: true);

  MyBookingState setError() => copyWith(error: Error());

  @override
  List<Object?> get props => [
    booking,
    error,
    isLoading,
    applyClubPoints,
    clubPoints,
    isTermsAccepted,
    showTermsError,
    _items,
  ];

  MyBookingState copyWith({
    Booking? booking,
    bool? applyClubPoints,
    Error? error,
    int? clubPoints,
    bool? isTermsAccepted,
    bool? showTermsError,
    Iterable<BookingAddonItem>? items,
  }) {
    return MyBookingState(
      booking: booking ?? this.booking,
      error: error ?? this.error,
      isLoading: isLoading,
      applyClubPoints: applyClubPoints ?? this.applyClubPoints,
      clubPoints: clubPoints ?? this.clubPoints,
      isTermsAccepted: isTermsAccepted ?? this.isTermsAccepted,
      showTermsError: showTermsError ?? this.showTermsError,
      items: items ?? _items,
    );
  }
}