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: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/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/utils/dark_theme_util.dart';

import '../../../router/page/property_page_router.dart';
import '../vm/property_vm.dart';

final tabsRouterKey = GlobalKey<AutoTabsRouterState>();
@RoutePage()
class PropertyPage extends HookConsumerWidget {
  const PropertyPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const PropertyPageRoute());
    } else {
      appRouter.push(const PropertyPageRoute());
    }
  }

  // 顶部tab 切换
  Widget _buildTopSection(BuildContext context, WidgetRef ref, _vm, tabsRouter) {
    final topSectionsData = _vm.topSectionsData;
    final currentTabIdx = tabsRouter.activeIndex;
    return Center(
      child: Container(
        color: context.appColors.whiteBG,
        width: MediaQuery.of(context).size.width,
        padding: const EdgeInsets.only(top: 0, bottom: 25),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: List.generate(topSectionsData.length, (index) {
            final item = topSectionsData[index];
            return Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Container(
                    width: MediaQuery.of(context).size.width / topSectionsData.length - 36,
                    // height: 70,
                    decoration: BoxDecoration(
                      color: ColorUtils.string2Color("#F0F8FF"),
                      shape: BoxShape.circle, // 设置为圆形
                      boxShadow: tabsRouter.activeIndex == index ? [
                        BoxShadow(
                          color: DarkThemeUtil.multiColors(context, context.appColors.tabLightBlueShadow, darkColor: AppColorsTheme.colorPrimary,)??context.appColors.tabLightBlueShadow, // 设置阴影颜色
                          blurRadius: 5, // 设置模糊半径
                          spreadRadius: 0.05, // 控制阴影扩散
                          offset: const Offset(0, 2), // 设置阴影偏移量
                        ),
                      ] : [],// 未选中时无阴影,
                    ),
                    child: MyAssetImage(
                      item['icon'],
                      width: MediaQuery.of(context).size.width / topSectionsData.length - 36,
                      height: 70,
                    ).onTap(() {
                        tabsRouter.setActiveIndex(index);
                      },
                      type: ClickType.throttle,
                    ),
                  ),
                  SizedBox.fromSize(size: const Size(0, 9)),
                  MyTextView(
                    item['title'],
                    maxLines: 1, // 设置最大行数为2
                    isTextEllipsis: true, // 超出部分用省略号表示
                    fontSize: 13,
                    textColor: index == currentTabIdx ? DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: AppColorsTheme.colorPrimary): context.appColors.textBlack,
                    isFontMedium: true,
                  ),
                ],
              ),
            );
          }),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final _vm = ref.read(propertyVmProvider.notifier);
    final state = ref.watch(propertyVmProvider);
    final isCollection = useState<int>(0);

    useEffect((){
      WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
        if(tabsRouterKey.currentState?.controller != null){
          tabsRouterKey.currentState?.controller?.addListener((){
            _vm.tabsRouterChange();
          });
        }
      });

      return (){
        Log.d("CommunityPage dispose");
        tabsRouterKey.currentState?.controller?.removeListener(_vm.tabsRouterChange);
      };
    },[]);
    return Scaffold(
        appBar: MyAppBar.appBar(
          context,
          S.current.property,
          backgroundColor: context.appColors.backgroundWhite,
          actions: [
             state.currentPageViewIdx == 1? MyAssetImage(
              isCollection.value ==1? Assets.propertyCollectionActive: Assets.propertyCollection,
              width: 22.5,
              height: 21,
            ).onTap((){
               isCollection.value = isCollection.value ==1?0:1;
              _vm.handlerCollectionFilter(context,isCollection.value);
            }):Container(),
            const SizedBox(width: 20),
          ],
        ),
        body: AutoTabsRouter.pageView(
          key: tabsRouterKey,
          routes: const [
            // PropertyIoanPageRoute(),
            PropertyNewsPageRoute(),
            PropertySalePageRoute(),
            PropertyRentPageRoute(),
          ],
          builder: (context, child, pageController) {
             final  tabsRouter = AutoTabsRouter.of(context);
             return Column(
               children: [
                 _buildTopSection(context, ref, _vm, tabsRouter),
                 Expanded(
                   child: child,
                 ),
              ],
             );
          },
        )
    );
  }
}
