import 'package:electronic_assistant/base/base_page.dart';
import 'package:electronic_assistant/module/agenda/task_item_view.dart';
import 'package:electronic_assistant/resource/colors.gen.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/expand.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../data/bean/agenda.dart';
import '../../data/repositories/account_repository.dart';
import '../../popup/agenda_time_popup.dart';
import '../../popup/common_popup.dart';
import '../../popup/template_utils.dart';
import '../../resource/assets.gen.dart';
import '../../router/app_pages.dart';
import '../chat/view.dart';
import 'controller.dart';

class AgendaPage extends BasePage<AgendaController> {
  const AgendaPage({super.key});

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        buildBgBox(),
        buildTopGradient(),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            AppBar(
              systemOverlayStyle: SystemUiOverlayStyle.dark,
              backgroundColor: Colors.transparent,
              leading: IconButton(
                icon: SizedBox(
                    width: 24.w,
                    height: 24.w,
                    child: Assets.images.iconBack.image()),
                // Custom icon
                onPressed: () {
                  Get.back();
                },
              ),
              title: Text(StringName.taskTitle.tr,
                  style: TextStyle(
                      fontSize: 17.sp,
                      fontWeight: FontWeight.bold,
                      color: ColorName.primaryTextColor)),
              centerTitle: true,
            ),
            // _buildSearchView(),
            // SizedBox(height: 12.h),
            // Obx(() {
            //   return Visibility(
            //     visible: controller.filterTxt.isNotEmpty,
            //     child: Container(
            //       margin: EdgeInsets.only(left: 12.w),
            //       padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
            //       decoration: BoxDecoration(
            //           color: const Color(0xFFE9E9E9),
            //           borderRadius: BorderRadius.circular(8.w)),
            //       child: IntrinsicWidth(
            //         child: Row(
            //           children: [
            //             Text(controller.filterTxt,
            //                 style: TextStyle(
            //                     fontSize: 13.sp,
            //                     color: ColorName.secondaryTextColor)),
            //             SizedBox(width: 6.w),
            //             GestureDetector(
            //               onTap: () {
            //                 controller.clearFilterTime();
            //               },
            //               child: Opacity(
            //                   opacity: 0.7,
            //                   child: ImageIcon(
            //                       Assets.images.iconTaskFilterClose.provider(),
            //                       size: 16.w)),
            //             )
            //           ],
            //         ),
            //       ),
            //     ),
            //   );
            // }),
            SizedBox(width: 7.h),
            Expanded(
                child: SmartRefresher(
              onLoading: controller.onLoadMoreDoneData,
              enablePullDown: false,
              enablePullUp: true,
              controller: controller.refreshController,
              child: CustomScrollView(slivers: [
                SliverToBoxAdapter(
                  child: Obx(() {
                    return taskGroupItem(
                        StringName.taskItemTodo.tr,
                        controller.agendaTodoList.length,
                        controller.todoIsExpanded.value, itemClick: () {
                      controller.onClickTodoGroup();
                    });
                  }),
                ),
                Obx(() {
                  return SliverList.builder(
                      itemBuilder: _buildTodoItem,
                      itemCount: controller.todoIsExpanded.value
                          ? controller.agendaTodoList.length
                          : 0);
                }),
                SliverToBoxAdapter(
                  child: Obx(() {
                    return taskGroupItem(
                        StringName.taskItemDone.tr,
                        controller.doneSize.value,
                        controller.doneIsExpanded.value, itemClick: () {
                      controller.onClickDoneGroup();
                    });
                  }),
                ),
                Obx(() {
                  return SliverList.builder(
                      itemBuilder: _buildDoneItem,
                      itemCount: controller.doneIsExpanded.value
                          ? controller.agendaDoneList.length
                          : 0);
                })
              ]),
            ))
          ],
        )
      ],
    );
  }

  Widget _buildSearchView() {
    return Row(
      children: [
        Expanded(
            child: Container(
          height: 36.h,
          margin: EdgeInsets.only(left: 12.w),
          decoration: BoxDecoration(
              color: ColorName.white, borderRadius: BorderRadius.circular(8.w)),
          padding: EdgeInsets.only(left: 12.w),
          child: Row(
            children: [
              Assets.images.iconSearch.image(width: 20.w, height: 20.w),
              SizedBox(width: 6.w),
              Text(
                StringName.searchHint.tr,
                style: TextStyle(
                    fontSize: 14.sp, color: ColorName.tertiaryTextColor),
              )
            ],
          ),
        )),
        Builder(builder: (context) {
          return GestureDetector(
            onTap: () {
              showAgendaTimePopup(
                  context, Alignment.bottomLeft, controller.timeFilterType,
                  callback: (type) {
                controller.onClickTimeType(type);
              });
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    margin: EdgeInsets.symmetric(horizontal: 16.w),
                    width: 20.w,
                    height: 20.w,
                    child: Assets.images.iconSift.image()),
                // Replace with your image asset
                SizedBox(height: 2.h),
                // Add some space between the image and text
                Text(
                  StringName.agendaSift.tr,
                  style: TextStyle(
                      fontSize: 10.sp, color: ColorName.primaryTextColor),
                ),
              ],
            ),
          );
        })
      ],
    );
  }

  Widget _buildTodoItem(BuildContext context, int index) {
    Agenda item = controller.agendaTodoList[index];
    return Builder(builder: (context) {
      return GestureDetector(
        onLongPressStart: (details) {
          if (!accountRepository.isLogin.value) {
            return;
          }
          showPressTouchPopup(details.globalPosition, Alignment.bottomRight,
              _buildListUpdatePopupView(item, controller.agendaDetailPopupTag),
              tag: controller.agendaDetailPopupTag);
        },
        child: taskItemView(
          item,
          onCheckClick: () {
            controller.agendaComplete(item, true);
          },
          onThinkingClick: () {
            ChatPage.startByTalkId(
                item.isExample == true
                    ? ChatFromType.fromTalkExample
                    : ChatFromType.fromAnalysisBtn,
                item.talkId,
                agenda: item);
          },
        ),
      );
    });
  }

  List<Widget> _buildListUpdatePopupView(Agenda item, String tag) {
    return [
      createNormalPopupItem(StringName.agendaDetailPopupCancel.tr,
          onItemClick: () {
        SmartDialog.dismiss(tag: tag);
        controller.onAgendaCancel(item);
      }),
      createPopupDivider(),
      createNormalPopupItem(StringName.agendaDetailPopupUpdate.tr,
          onItemClick: () {
        SmartDialog.dismiss(tag: tag);
        controller.onAgendaUpdate(item);
      }),
    ];
  }

  Widget _buildDoneItem(BuildContext context, int index) {
    Agenda item = controller.agendaDoneList[index];
    return taskItemView(item, onCheckClick: () {
      controller.agendaComplete(item, false);
    }, isShowAnalyse: false);
  }

  Container buildTopGradient() {
    return Container(
        width: 1.sw,
        height: 112.h,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: ['#E8EBFF'.toColor(), '#00E8EBFF'.toColor()],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            stops: const [0.3, 1.0],
          ),
        ) // 其他子小部件
        );
  }

  DecoratedBox buildBgBox() {
    return DecoratedBox(
        decoration: BoxDecoration(color: '#F6F6F6'.toColor()),
        child: Container(
          height: double.infinity,
        ));
  }

  @override
  bool immersive() {
    return true;
  }

  Widget taskGroupItem(String groupName, int count, bool isExpanded,
      {VoidCallback? itemClick}) {
    return GestureDetector(
      onTap: itemClick,
      child: Container(
        color: Colors.transparent,
        padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 12.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(groupName,
                style: TextStyle(
                    fontSize: 14.sp, color: ColorName.secondaryTextColor)),
            //占位填充
            const Spacer(),
            Row(
              children: [
                Text('$count${StringName.taskItemDesc.tr}',
                    style: TextStyle(
                        fontSize: 12.sp, color: ColorName.secondaryTextColor)),
                SizedBox(width: 4.w),
                SizedBox(
                    width: 16.w,
                    height: 16.h,
                    child: isExpanded
                        ? Assets.images.iconTalkExpand.image()
                        : Assets.images.iconTalkCollapse.image())
              ],
            )
          ],
        ),
      ),
    );
  }
}
