import 'package:cpt_main/modules/home/home_state.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:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:auto_route/auto_route.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:router/componentRouter/community_service.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';

import 'item_home_category.dart';
import 'home_view_model.dart';
import 'item_home_last_news.dart';
import 'item_home_last_trans.dart';
import 'item_home_manage_guide.dart';
import 'item_home_property_news.dart';

@RoutePage()
class HomePage extends HookConsumerWidget {
  const HomePage({super.key});

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

    return Scaffold(
      appBar: MyAppBar.appBar(context, "Good Afternoon,Mike",
          backIconPath: Assets.mainTabMeSelected,
          backIconWidth: 18.5,
          backIconHeight: 20,
          showBackButton: true,
          backgroundColor: context.appColors.whiteBG,
          backCallback: (){
          ToastEngine.show("测试去登录页面");
          ComponentServiceManager().authService.startLoginPage();
          },
          actions: [
            Center(
                    child: Stack(
              clipBehavior: Clip.none, // 不裁剪超出边界的内容
              alignment: Alignment.topLeft,
              children: <Widget>[
                // 通知图标
                const MyAssetImage(Assets.mainHomeNotificationIcon, width: 19, height: 20),

                //未读消息
                Positioned(
                  left: 0,
                  top: 0,
                  child: Transform.translate(
                    offset: const Offset(-10, -5),
                    child: MyTextView(
                      "99",
                      boxWidth: 20.0,
                      textColor: Colors.white,
                      fontSize: 10,
                      isFontLight: true,
                      backgroundColor: context.appColors.redDefault,
                      cornerRadius: 8,
                      paddingTop: 2,
                      paddingBottom: 2,
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ],
            ).onTap(viewModel.gotoNotificationPage))
                .marginOnly(right: 15),
          ],
          showBottomDivider: true),
      backgroundColor: context.appColors.backgroundDefault,
      body: CustomScrollView(
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        slivers: [
          //支付与奖励
          _buildPaymentAndRewardsWidget(context, ref),

          //间距
          _buildSliverSpace(20),

          //九宫选项组 （固定）
          _buildCategoryWidget(context, ref),

          //轮播图片 （动态）
          _buildBannerImage(),

          //最新的新闻（动态）
          _buildLastNews(context, ref),

          //最新的交易
          SliverToBoxAdapter(
            child: MyTextView(
              marginTop: 14,
              marginLeft: 15,
              marginBottom: 14,
              S.current.latest_transactions,
              textColor: context.appColors.textPrimary,
              fontSize: 16,
              isFontMedium: true,
            ),
          ),

          //最新交易列表 （动态）
          _buildLastTransaction(context, state),

          //房产新闻
          SliverToBoxAdapter(
            child: MyTextView(
              marginTop: 14,
              marginLeft: 15,
              marginBottom: 14,
              onClick: viewModel.gotoPropertyNewsPage,
              S.current.property_news,
              textColor: context.appColors.textPrimary,
              fontSize: 16,
              isFontMedium: true,
            ),
          ),

          //房产新闻列表 （动态）
          _buildPropertyNews(context, state),

          //管理员介绍 (固定)
          _buildManagementGuides(context, ref),

          //间距
          _buildSliverSpace(15),
        ],
      ),
    );
  }

  //顶部的支付与奖励的布局
  Widget _buildPaymentAndRewardsWidget(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(homeViewModelProvider.notifier);

    return SliverToBoxAdapter(
      child: Container(
        color: context.appColors.whiteBG,
        width: double.infinity,
        height: 45,
        child: Column(
          children: [
            Row(
              children: [
                Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const MyAssetImage(Assets.mainHomePaymentIcon, width: 16.5, height: 18).marginOnly(left: 20),
                    MyTextView(
                      S.current.payment,
                      textColor: context.appColors.textBlack,
                      fontSize: 15,
                      isFontMedium: true,
                    ).paddingOnly(left: 13, right: 13).expanded(),
                    const MyAssetImage(Assets.mainHomeMoreIcon, width: 6, height: 8.5).marginOnly(right: 15),
                  ],
                ).onTap(viewModel.gotoPaymentPage).expanded(),
                Container(color: context.appColors.dividerDefault, width: 0.5, height: double.infinity),
                Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const MyAssetImage(Assets.mainHomeRewardsIcon, width: 16.5, height: 17).marginOnly(left: 20),
                    MyTextView(
                      S.current.rewards,
                      textColor: context.appColors.textBlack,
                      fontSize: 15,
                      isFontMedium: true,
                    ).paddingOnly(left: 13, right: 4).expanded(),
                    MyTextView(
                      "9568",
                      textColor: context.appColors.textBlack,
                      fontSize: 15,
                      isFontBold: true,
                    ).paddingOnly(left: 1, right: 4),
                    const MyAssetImage(Assets.mainHomeMoreIcon, width: 6, height: 8.5).marginOnly(right: 15),
                  ],
                ).onTap(viewModel.gotoRewardsPage).expanded(),
              ],
            ).expanded(),
            //底部分割线
            Container(color: context.appColors.dividerDefault, height: 0.5, width: double.infinity),
          ],
        ),
      ),
    );
  }

  Widget _buildSliverSpace(double size) {
    return SliverToBoxAdapter(
      child: SizedBox(height: size),
    );
  }

  //九宫格选项组
  Widget _buildCategoryWidget(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(homeViewModelProvider.notifier);
    final state = ref.watch(homeViewModelProvider);

    return SliverGrid(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3, // 三列
        mainAxisSpacing: 10.0, // 主轴（上下）的间距
        crossAxisSpacing: 0.0, // 交叉轴（左右）的间距
        childAspectRatio: 9 / 8, // 子组件的宽高比
      ),
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return HomeCategoryItem(
            category: state.homeCategory[index],
          ).onTap(() {
            viewModel.switchCategory(index);
          }); // 生成每个网格项
        },
        childCount: state.homeCategory.length, // 总共的网格项数
      ),
    );
  }

  //Banner的布局
  Widget _buildBannerImage() {
    return SliverToBoxAdapter(
      child: Center(
        child: MyLoadImage(
          "https://t11.baidu.com/it/u=1326770860,192430039&fm=30&app=106&f=JPEG?w=640&h=427&s=33B5BFAA6A165BCA182937620300D077",
          width: 345,
          height: 152.5,
          cornerRadius: 5,
        ),
      ).marginOnly(top: 21),
    );
  }

  //最新新闻
  Widget _buildLastNews(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(homeViewModelProvider.notifier);
    final state = ref.watch(homeViewModelProvider);

    return SliverToBoxAdapter(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        MyTextView(
          S.current.latest_news,
          fontSize: 16,
          marginTop: 14,
          marginBottom: 14,
          isFontMedium: true,
          onClick: viewModel.gotoLastNewsPage,
          textColor: context.appColors.textPrimary,
        ),
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          physics: const BouncingScrollPhysics(),
          clipBehavior: Clip.none,
          child: Row(
            children: List.generate(state.lastNews.length, (index) {
              return LastNewsItem(
                lastNews: state.lastNews[index],
              );
            }),
          ),
        )
      ],
    ).paddingOnly(left: 15, right: 15));
  }

  //最新的交易列表
  Widget _buildLastTransaction(BuildContext context, HomeState state) {
    return SliverPadding(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      sliver: DecoratedSliver(
        decoration: BoxDecoration(
          color: context.appColors.whiteBG,
          borderRadius: BorderRadius.circular(5.0),
          boxShadow: [
            BoxShadow(
              color: const Color(0xFF656565).withOpacity(0.1),
              offset: const Offset(0, 1.5),
              blurRadius: 2.5,
              spreadRadius: 1.5,
            ),
          ],
        ),
        sliver: SliverPadding(
          padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
          sliver: SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  child: LastTransItem(
                    lastTrans: state.lastTrans[index],
                  ),
                );
              },
              childCount: state.lastTrans.length,
            ),
          ),
        ),
      ),
    );
  }

  //房产新闻的双列表
  Widget _buildPropertyNews(BuildContext context, HomeState state) {
    return SliverList(
      delegate: SliverChildListDelegate(
        [
          // PropertyNews(),

          // 第一个水平滑动列表
          _buildPropertyNewsHorizontalList(),

          const SizedBox(height: 10),

          // // 第二个水平滑动列表
          _buildPropertyNewsHorizontalList(),
        ],
      ),
    );
  }

  Widget _buildPropertyNewsHorizontalList() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      physics: const BouncingScrollPhysics(),
      clipBehavior: Clip.none,
      child: Row(
        children: List.generate(5, (index) {
          return PropertyNews();
        }),
      ).marginOnly(left: 15, right: 15),
    );
  }

  //管理员介绍
  Widget _buildManagementGuides(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(homeViewModelProvider.notifier);
    final state = ref.watch(homeViewModelProvider);

    return SliverToBoxAdapter(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        MyTextView(
          S.current.strata_management_guides,
          fontSize: 16,
          marginTop: 14,
          marginBottom: 14,
          onClick: viewModel.gotoManageGuidePage,
          isFontMedium: true,
          textColor: context.appColors.textPrimary,
        ),
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          physics: const BouncingScrollPhysics(),
          clipBehavior: Clip.none,
          child: Row(
            children: List.generate(state.manage_guide.length, (index) {
              return ManageGuideItem(
                manageGuide: state.manage_guide[index],
              );
            }),
          ),
        )
      ],
    ).paddingOnly(left: 15, right: 15));
  }
}
