import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/models/bookable_space_model.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/params/non_bookable_spaces_params.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/presentation/blocs/non_bookable_spaces_bloc/non_bookaable_spaces_bloc.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/presentation/widgets/search_unbookable_spaces_widget.dart';
import 'package:syncrow_web/pages/space_management_v2/main_module/shared/models/paginated_data_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class SpacesStepDetailsWidget extends StatefulWidget {
  const SpacesStepDetailsWidget({
    super.key,
  });

  @override
  State<SpacesStepDetailsWidget> createState() =>
      _SpacesStepDetailsWidgetState();
}

class _SpacesStepDetailsWidgetState extends State<SpacesStepDetailsWidget> {
  Timer? _debounce;
  ScrollController scrollController = ScrollController();
  int currentPage = 1;
  String? currentSearchTerm;
  bool isLoadingMore = false;

  @override
  void initState() {
    super.initState();

    scrollController.addListener(() {
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent - 100) {
        final state = context.read<NonBookableSpacesBloc>().state;
        if (state is NonBookableSpacesLoaded &&
            state.nonBookableSpaces.hasNext &&
            !isLoadingMore) {
          isLoadingMore = true;
          currentPage++;
          context.read<NonBookableSpacesBloc>().add(
                LoadUnBookableSpacesEvent(
                  nonBookableSpacesParams: NonBookableSpacesParams(
                    currentPage: currentPage,
                    searchedWords: currentSearchTerm,
                  ),
                ),
              );
        }
      }
    });
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Select Space',
          style: TextStyle(
            fontWeight: FontWeight.w700,
            color: ColorsManager.blackColor,
          ),
        ),
        const SizedBox(
          height: 20,
        ),
        Container(
          width: 450,
          height: 480,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
            boxShadow: const [
              BoxShadow(
                color: Color(0x40000000),
                offset: Offset.zero,
                blurRadius: 5,
              ),
            ],
          ),
          child: Column(
            children: [
              Container(
                width: 520,
                height: 70,
                padding:
                    const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
                decoration: const BoxDecoration(
                  color: Color(0xFFF8F8F8),
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(20),
                  ),
                ),
                child: SearchUnbookableSpacesWidget(
                  title: 'Search',
                  onChanged: (p0) {
                    if (_debounce?.isActive ?? false) _debounce!.cancel();
                    _debounce = Timer(const Duration(milliseconds: 500), () {
                      currentSearchTerm = p0;
                      currentPage = 1;
                      context.read<NonBookableSpacesBloc>().add(
                            LoadUnBookableSpacesEvent(
                              nonBookableSpacesParams: NonBookableSpacesParams(
                                currentPage: currentPage,
                                searchedWords: currentSearchTerm,
                              ),
                            ),
                          );
                    });
                  },
                ),
              ),
              Expanded(
                child:
                    BlocConsumer<NonBookableSpacesBloc, NonBookableSpacesState>(
                  listener: (context, state) {
                    if (state is NonBookableSpacesLoaded) {
                      isLoadingMore = false;
                    }
                  },
                  builder: (context, state) {
                    if (state is NonBookableSpacesError) {
                      return Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(state.error),
                          const SizedBox(
                            height: 5,
                          ),
                          ElevatedButton(
                              onPressed: () {
                                context.read<NonBookableSpacesBloc>().add(
                                      LoadUnBookableSpacesEvent(
                                        nonBookableSpacesParams:
                                            NonBookableSpacesParams(
                                          currentPage: currentPage,
                                          searchedWords: currentSearchTerm,
                                        ),
                                      ),
                                    );
                              },
                              child: const Text('Try Again'))
                        ],
                      );
                    } else if (state is NonBookableSpacesLoading) {
                      if (state.lastNonBookableSpaces == null) {
                        return const Center(
                          child: CircularProgressIndicator(),
                        );
                      } else {
                        return UnbookableListWidget(
                          scrollController: scrollController,
                          nonBookableSpaces: state.lastNonBookableSpaces!,
                        );
                      }
                    } else if (state is NonBookableSpacesLoaded) {
                      return UnbookableListWidget(
                        scrollController: scrollController,
                        nonBookableSpaces: state.nonBookableSpaces,
                      );
                    } else {
                      return const SizedBox();
                    }
                  },
                ),
              )
            ],
          ),
        )
      ],
    );
  }
}

class UnbookableListWidget extends StatelessWidget {
  final PaginatedDataModel<BookableSpacemodel> nonBookableSpaces;
  const UnbookableListWidget({
    super.key,
    required this.scrollController,
    required this.nonBookableSpaces,
  });

  final ScrollController scrollController;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 490,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(20),
        ),
      ),
      padding: const EdgeInsets.only(top: 10, left: 20, bottom: 5),
      child: ListView.separated(
        separatorBuilder: (context, index) => const SizedBox(
          height: 5,
        ),
        controller: scrollController,
        itemCount: nonBookableSpaces.data.length,
        itemBuilder: (context, index) {
          if (index < nonBookableSpaces.data.length) {
            return CheckBoxSpaceWidget(
              nonBookableSpace: nonBookableSpaces.data[index],
            );
          } else {
            return const Padding(
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Center(child: CircularProgressIndicator()),
            );
          }
        },
      ),
    );
  }
}

class CheckBoxSpaceWidget extends StatefulWidget {
  final BookableSpacemodel nonBookableSpace;

  const CheckBoxSpaceWidget({
    super.key,
    required this.nonBookableSpace,
  });

  @override
  State<CheckBoxSpaceWidget> createState() => _CheckBoxSpaceWidgetState();
}

class _CheckBoxSpaceWidgetState extends State<CheckBoxSpaceWidget> {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Checkbox(
          value: isChecked,
          onChanged: (value) => setState(() {
            isChecked = value ?? false;
            if (isChecked) {
              context.read<NonBookableSpacesBloc>().add(
                    AddToBookableSpaceEvent(
                      nonBookableSpace: widget.nonBookableSpace,
                    ),
                  );
            } else {
              context.read<NonBookableSpacesBloc>().add(
                    RemoveFromBookableSpaceEvent(
                      bookableSpace: widget.nonBookableSpace,
                    ),
                  );
            }
          }),
        ),
        const SizedBox(
          width: 5,
        ),
        Expanded(child: Text(widget.nonBookableSpace.spaceName)),
      ],
    );
  }
}
