import 'dart:math';

import 'package:cpt_facility/modules/location/facility_location_page.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/facility_book_entity.dart';
import 'package:domain/entity/facility_index_entity.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/shatter/select_calendar/calendar_bottom_sheet.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';

import '../../router/page/facility_page_router.dart';
import 'facility_booking_view_model.dart';

@RoutePage()
class FacilityBookingPage extends HookConsumerWidget {
  final FacilityIndexEntity facilityEntity;

  const FacilityBookingPage({Key? key, required this.facilityEntity}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context, required FacilityIndexEntity facilityEntity}) {
    if (context != null) {
      context.router.push(FacilityBookingPageRoute(facilityEntity: facilityEntity));
    } else {
      appRouter.push(FacilityBookingPageRoute(facilityEntity: facilityEntity));
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.watch(facilityBookingViewModelProvider.notifier);
    final state = ref.watch(facilityBookingViewModelProvider);

    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() {
        viewModel.setFacilityId(facilityEntity.id, facilityEntity.name);
        viewModel.fetchListByDate();
      });
      return () {
        // 组件卸载时执行
      };
    }, []);

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        facilityEntity.name ?? "",
        backgroundColor: context.appColors.backgroundWhite,
        actions: [
          //去设施小区的定位图片
          Visibility(
            visible: facilityEntity.mapResources.isNotEmpty,
            child: MyAssetImage(
              Assets.facilityTitleLocationIcon,
              width: 44,
              height: 44,
              color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
            ).marginOnly(right: 3).onTap(() {
              FacilityLocationPage.startInstance(context: context, imageUrls: facilityEntity.mapResources);
            }),
          )
        ],
      ),
      backgroundColor: context.appColors.backgroundDark,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          //顶部的选中的日期与日历选择
          Row(
            mainAxisSize: MainAxisSize.max,
            children: [
              MyTextView(
                "${DateTimeUtils.getWeekday(state.selectedDate, languageCode: 'en')}, ${DateTimeUtils.formatDate(state.selectedDate, format: 'dd MMM yyyy')}",
                textColor: context.appColors.textBlack,
                fontSize: 17,
                marginTop: 18,
                marginBottom: 16,
                marginLeft: 15,
                isFontMedium: true,
              ).expanded(),
              MyAssetImage(
                Assets.facilityConfirmDateIcon,
                width: 22.5,
                height: 22.5,
                color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
              ).marginOnly(right: 10).onTap(() {
                //日历日期选择器
                _datePickerBottomSheet(context, ref);
              }, padding: 5),
            ],
          ),

          //二周的日期选择 (自定义控件)
          WeeklyCalendar(
            selectedDate: state.selectedDate,
            maxDate: DateTime.now().add(Duration(days: state.bookAdvanceDays)),
            onChangedSelectedDate: (dateTime) {
              viewModel.changeSelectedDate(dateTime);
            },
          ),

          //每天的单独数据
          LoadStateLayout(
            state: state.loadingState,
            errorMessage: state.errorMessage,
            errorRetry: () {
              viewModel.retryRequest();
            },
            successSliverWidget: [
              SliverToBoxAdapter(
                child: MyTextView(
                  S.current.quota_left_msg(state.data?.remainQuota ?? 0, state.data?.quotaResetOn ?? "-"),
                  marginTop: 7,
                  marginLeft: 10,
                  marginBottom: 15,
                  textColor: context.appColors.textBlack,
                  fontSize: 12,
                  isFontMedium: true,
                ),
              ),
              SliverList(
                  delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return _buildFacilityOption(context, ref, state.data?.facilities?[index], index);
                },
                childCount: state.data?.facilities?.length,
              ))
            ],
          ).marginOnly(top: 5).expanded(),

          //底部按钮
          MyButton(
            onPressed: viewModel.gotoConfirmPage,
            text: S.current.next,
            textColor: Colors.white,
            backgroundColor: context.appColors.btnBgDefault,
            fontWeight: FontWeight.w500,
            type: ClickType.throttle,
            fontSize: 16,
            minHeight: 50,
            radius: 0,
          )
        ],
      ),
    );
  }

  //日期日历的选择器，底部弹窗选择
  void _datePickerBottomSheet(BuildContext context, WidgetRef ref) {
    final viewModel = ref.watch(facilityBookingViewModelProvider.notifier);
    final state = ref.watch(facilityBookingViewModelProvider);

    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(30.0), topRight: Radius.circular(30.0)),
      ),
      builder: (BuildContext context) {
        return CustomCalendarBottomSheet(
          firstDate: DateTime.now(),
          lastDate: DateTime.now().add(Duration(days: state.bookAdvanceDays)),
          selectedDate: state.selectedDate,
          locale: "en",
          onDateChange: (dateTime) {
            Navigator.pop(context);
            viewModel.changeSelectedDate(dateTime);
          },
        );
      },
    );
  }

  //生产当前设施的选项
  Widget _buildFacilityOption(BuildContext context, WidgetRef ref, FacilityBookFacilities? item, int index) {
    final viewModel = ref.watch(facilityBookingViewModelProvider.notifier);
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 38,
          color: context.appColors.btnBgDefault,
          child: Center(
            child: MyTextView(
              item?.name ?? "",
              fontSize: 16,
              textColor: Colors.white,
              textAlign: TextAlign.center,
              isFontMedium: true,
            ),
          ),
        ),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            childAspectRatio: 82 / 43,
            mainAxisSpacing: 6.5,
            crossAxisSpacing: 6.5,
          ),
          itemCount: item?.periods?.length,
          itemBuilder: (context, innerIndex) {
            return Container(
              decoration: BoxDecoration(
                color: item?.periods?[innerIndex].selected == true
                    ? context.appColors.orangeBG
                    : item?.periods?[innerIndex].enable == true
                        ? context.appColors.whiteBG
                        : context.appColors.disEnableGray,
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center, // 垂直居中
                children: [
                  MyTextView(
                    item?.periods?[innerIndex].start ?? "",
                    fontSize: 12,
                    textColor: item?.periods?[innerIndex].selected == true ? context.appColors.textWhite : context.appColors.textBlack,
                    isFontMedium: true,
                  ),
                  MyTextView(
                    item?.periods?[innerIndex].end ?? "",
                    fontSize: 12,
                    textColor: item?.periods?[innerIndex].selected == true ? context.appColors.textWhite : context.appColors.textBlack,
                    isFontMedium: true,
                  ),
                ],
              ),
            ).onTap(() {
              //点击选中,可用并且未选中的情况下点击选中
              if (item?.periods?[innerIndex].enable == true && item?.periods?[innerIndex].selected == false) {
                viewModel.selectPeriods(index, innerIndex);
              }
            });
          },
        ).marginSymmetric(horizontal: 10, vertical: 17),
      ],
    );
  }
}
