import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/pages/access_management/booking_system/view/widgets/icon_text_button.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/data/remote_bookable_spaces_service.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/bookable_spaces_params.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/presentation/blocs/bookable_spaces_bloc/bookable_spaces_bloc.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/presentation/screens/setup_bookable_spaces_dialog.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/presentation/widgets/custom_data_table.dart';
import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/theme/responsive_text_theme.dart';
import 'package:syncrow_web/web_layout/web_scaffold.dart';

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

  @override
  State<ManageBookableSpacesPage> createState() =>
      _ManageBookableSpacesPageState();
}

class _ManageBookableSpacesPageState extends State<ManageBookableSpacesPage> {
  final PageController _pageController = PageController(initialPage: 1);
  int _currentPageIndex = 1;
  @override
  Widget build(BuildContext context) {
    return WebScaffold(
      enableMenuSidebar: false,
      appBarTitle: Text(
        'Access Management',
        style: ResponsiveTextTheme.of(context).deviceManagementTitle,
      ),
      centerBody: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextButton(
            onPressed: () => _switchPage(0),
            child: Text(
              'Access Overview',
              style: context.textTheme.titleMedium?.copyWith(
                color: _currentPageIndex == 0 ? Colors.white : Colors.grey,
                fontWeight:
                    _currentPageIndex == 0 ? FontWeight.w700 : FontWeight.w400,
              ),
            ),
          ),
          TextButton(
            onPressed: () => _switchPage(1),
            child: Text(
              'Booking System',
              style: context.textTheme.titleMedium?.copyWith(
                color: _currentPageIndex == 1 ? Colors.white : Colors.grey,
                fontWeight:
                    _currentPageIndex == 1 ? FontWeight.w700 : FontWeight.w400,
              ),
            ),
          ),
        ],
      ),
      rightBody: const NavigateHomeGridView(),
      scaffoldBody: BlocProvider(
        create: (context) => BookableSpacesBloc(
          RemoteBookableSpacesService(HTTPService()),
        )..add(LoadBookableSpacesEvent(
            BookableSpacesParams(currentPage: 1),
          )),
        child: const ManageBookableSpacesWidget(),
      ),
    );
  }

  void _switchPage(int index) {
    setState(() => _currentPageIndex = index);
    _pageController.jumpToPage(index);
  }
}

class ManageBookableSpacesWidget extends StatelessWidget {
  const ManageBookableSpacesWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          Expanded(
              flex: 10,
              child: Padding(
                padding: const EdgeInsetsGeometry.symmetric(vertical: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SvgTextButton(
                        svgSize: 15,
                        fontSize: 10,
                        fontWeight: FontWeight.bold,
                        svgAsset: Assets.backButtonIcon,
                        label: 'Booking Home',
                        onPressed: () {
                          context.pop();
                        }),
                    SvgTextButton(
                      svgSize: 15,
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                      svgAsset: Assets.addButtonIcon,
                      label: 'Set Up a Bookable Spaces',
                      onPressed: () {
                        final bloc = context.read<BookableSpacesBloc>();
                        showDialog(
                          context: context,
                          builder: (context) => BlocProvider.value(
                            value: bloc,
                            child: SetupBookableSpacesDialog(),
                          ),
                        );
                      },
                    )
                  ],
                ),
              )),
          const SizedBox(
            height: 10,
          ),
          Expanded(
            flex: 85,
            child: BlocBuilder<BookableSpacesBloc, BookableSpacesState>(
              builder: (context, state) {
                if (state is BookableSpacesLoading) {
                  return const Center(child: CircularProgressIndicator());
                } else if (state is BookableSpacesError) {
                  return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(state.error),
                        const SizedBox(
                          height: 5,
                        ),
                        ElevatedButton(
                            onPressed: () => context
                                .read<BookableSpacesBloc>()
                                .add(LoadBookableSpacesEvent(
                                  BookableSpacesParams(currentPage: 1),
                                )),
                            child: const Text('try Again'))
                      ]);
                } else if (state is BookableSpacesLoaded) {
                  return CustomDataTable<BookableSpacemodel>(
                    items: state.bookableSpacesList.data,
                    cellsWidgets: (space) => [
                      DataCell(
                        Padding(
                            padding: const EdgeInsetsGeometry.only(left: 10),
                            child: Text(
                              space.spaceName,
                              style: const TextStyle(fontSize: 11),
                            )),
                      ),
                      DataCell(Padding(
                          padding: const EdgeInsetsGeometry.only(left: 10),
                          child: Text(
                            space.spaceVirtualAddress,
                            style: const TextStyle(fontSize: 11),
                          ))),
                      DataCell(Container(
                        padding: const EdgeInsetsGeometry.only(left: 10),
                        width: 200,
                        child: Wrap(
                          spacing: 4,
                          children: space.spaceConfig!.bookableDays
                              .map((day) => Text(
                                    day,
                                    style: const TextStyle(fontSize: 11),
                                  ))
                              .toList(),
                        ),
                      )),
                      DataCell(
                        Padding(
                          padding: const EdgeInsetsGeometry.only(left: 10),
                          child: Text(
                            space.spaceConfig!.bookingStartTime!
                                .format(context),
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                      ),
                      DataCell(
                        Padding(
                          padding: const EdgeInsetsGeometry.only(left: 10),
                          child: Text(
                            space.spaceConfig!.bookingEndTime!.format(context),
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                      ),
                      DataCell(Padding(
                          padding: const EdgeInsetsGeometry.only(left: 10),
                          child: Text(
                            '${space.spaceConfig!.cost} Points',
                            style: const TextStyle(fontSize: 11),
                          ))),
                      DataCell(Center(
                        child: Transform.scale(
                          scale: 0.7,
                          child: Switch(
                            value: space.spaceConfig!.availability,
                            trackColor: WidgetStateProperty.resolveWith<Color>(
                                (Set<WidgetState> states) {
                              return ColorsManager.blue1;
                            }),
                            inactiveTrackColor: ColorsManager.lightGrayColor,
                            thumbColor: WidgetStateProperty.resolveWith<Color>(
                                (Set<WidgetState> states) {
                              return ColorsManager.whiteColors;
                            }),
                            onChanged: (value) {},
                          ),
                        ),
                      )),
                      DataCell(Center(
                        child: ElevatedButton(
                          onPressed: () {},
                          style: ElevatedButton.styleFrom(
                            padding: EdgeInsets.zero,
                            fixedSize: const Size(50, 30),
                            elevation: 1,
                          ),
                          child: SvgPicture.asset(
                            Assets.settings,
                            height: 15,
                            color: ColorsManager.blue1,
                          ),
                        ),
                      )),
                    ],
                    columnsTitles: const [
                      'Space',
                      'Space Virtual Address',
                      'Bookable Days',
                      'Booking Start Time',
                      'Booking End Time',
                      'Cost',
                      'Availability',
                      'Settings',
                    ],
                  );
                } else {
                  return const SizedBox();
                }
              },
            ),
          ),
          const SizedBox(
            height: 5,
          ),
          Expanded(
            flex: 5,
            child: BlocBuilder<BookableSpacesBloc, BookableSpacesState>(
              builder: (context, state) {
                if (state is BookableSpacesLoaded) {
                  final totalPages = state.bookableSpacesList.totalPages;
                  final currentPage = state.bookableSpacesList.page;

                  List<Widget> paginationItems = [];

                  // « Two pages back
                  if (currentPage > 2) {
                    paginationItems.add(
                      _buildArrowButton(
                        label: '«',
                        onTap: () {
                          context.read<BookableSpacesBloc>().add(
                                LoadBookableSpacesEvent(
                                  BookableSpacesParams(
                                      currentPage: currentPage - 2),
                                ),
                              );
                        },
                      ),
                    );
                  }

                  // < One page back
                  if (currentPage > 1) {
                    paginationItems.add(
                      _buildArrowButton(
                        label: '<',
                        onTap: () {
                          context.read<BookableSpacesBloc>().add(
                                LoadBookableSpacesEvent(
                                  BookableSpacesParams(
                                      currentPage: currentPage - 1),
                                ),
                              );
                        },
                      ),
                    );
                  }

                  // Page numbers
                  for (int i = 1; i <= totalPages; i++) {
                    paginationItems.add(
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 4),
                        child: GestureDetector(
                          onTap: () {
                            if (i != currentPage) {
                              context.read<BookableSpacesBloc>().add(
                                    LoadBookableSpacesEvent(
                                      BookableSpacesParams(currentPage: i),
                                    ),
                                  );
                            }
                          },
                          child: Container(
                            width: 30,
                            height: 30,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: i == currentPage
                                  ? ColorsManager.dialogBlueTitle
                                  : Colors.grey[300],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              '$i',
                              style: TextStyle(
                                color: i == currentPage
                                    ? Colors.white
                                    : Colors.black,
                                fontWeight: i == currentPage
                                    ? FontWeight.bold
                                    : FontWeight.normal,
                              ),
                            ),
                          ),
                        ),
                      ),
                    );
                  }

                  // > One page forward
                  if (currentPage < totalPages) {
                    paginationItems.add(
                      _buildArrowButton(
                        label: '>',
                        onTap: () {
                          context.read<BookableSpacesBloc>().add(
                                LoadBookableSpacesEvent(
                                  BookableSpacesParams(
                                      currentPage: currentPage + 1),
                                ),
                              );
                        },
                      ),
                    );
                  }

                  // » Two pages forward
                  if (currentPage + 1 < totalPages) {
                    paginationItems.add(
                      _buildArrowButton(
                        label: '»',
                        onTap: () {
                          context.read<BookableSpacesBloc>().add(
                                LoadBookableSpacesEvent(
                                  BookableSpacesParams(
                                      currentPage: currentPage + 2),
                                ),
                              );
                        },
                      ),
                    );
                  }

                  return Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: paginationItems,
                  );
                } else {
                  return const SizedBox.shrink();
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildArrowButton(
      {required String label, required VoidCallback onTap}) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            label,
            style: const TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}
