import 'package:flutter_bloc/flutter_bloc.dart';
import '../models/booking_model.dart';
import '../viewmodels/booking_viewmodel.dart';

abstract class BookingEvent {}

class LoadBookings extends BookingEvent {
  final DateTime month;
  LoadBookings(this.month);
}

class SelectDate extends BookingEvent {
  final DateTime date;
  SelectDate(this.date);
}

class ToggleSlotExpand extends BookingEvent {
  final int attractionIndex;
  ToggleSlotExpand(this.attractionIndex);
}

class BookingState {
  final DateTime focusedMonth;
  final DateTime? selectedDate;
  final List<BookingDay> bookings;
  final bool isLoading;
  final List<int> expandedAttractions;

  BookingState({
    required this.focusedMonth,
    required this.selectedDate,
    required this.bookings,
    required this.isLoading,
    required this.expandedAttractions,
  });

  factory BookingState.initial() => BookingState(
    focusedMonth: DateTime.now(),
    selectedDate: null,
    bookings: [],
    isLoading: false,
    expandedAttractions: [],
  );

  BookingState copyWith({
    DateTime? focusedMonth,
    DateTime? selectedDate,
    List<BookingDay>? bookings,
    bool? isLoading,
    List<int>? expandedAttractions,
  }) {
    return BookingState(
      focusedMonth: focusedMonth ?? this.focusedMonth,
      selectedDate: selectedDate ?? this.selectedDate,
      bookings: bookings ?? this.bookings,
      isLoading: isLoading ?? this.isLoading,
      expandedAttractions: expandedAttractions ?? this.expandedAttractions,
    );
  }
}

class BookingBloc extends Bloc<BookingEvent, BookingState> {
  final BookingViewModel viewModel;

  BookingBloc({required this.viewModel}) : super(BookingState.initial()) {
    on<LoadBookings>(_onLoadBookings);
    on<SelectDate>(_onSelectDate);
    on<ToggleSlotExpand>(_onToggleSlotExpand);
  }

  Future<void> _onLoadBookings(
      LoadBookings event, Emitter<BookingState> emit) async {
    emit(state.copyWith(isLoading: true, focusedMonth: event.month));
    final data = await viewModel.getBookings(event.month);
    emit(state.copyWith(isLoading: false, bookings: data));
  }

  void _onSelectDate(SelectDate event, Emitter<BookingState> emit) {
    emit(state.copyWith(selectedDate: event.date));
  }

  void _onToggleSlotExpand(ToggleSlotExpand event, Emitter<BookingState> emit) {
    final expanded = List<int>.from(state.expandedAttractions);
    if (expanded.contains(event.attractionIndex)) {
      expanded.remove(event.attractionIndex);
    } else {
      expanded.add(event.attractionIndex);
    }
    emit(state.copyWith(expandedAttractions: expanded));
  }
}
