import 'package:electronic_assistant/base/base_page.dart';
import 'package:electronic_assistant/data/bean/talks.dart';
import 'package:electronic_assistant/module/files/controller.dart';
import 'package:electronic_assistant/module/talk/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/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../data/repositories/account_repository.dart';
import '../../dialog/rename_dialog.dart';
import '../../dialog/talk_delete_dialog.dart';
import '../../popup/talk_popup.dart';
import '../../resource/assets.gen.dart';

class FilesPage extends BasePage<FilesController> {
  const FilesPage({super.key});

  @override
  bool immersive() {
    return true;
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromRGBO(246, 245, 248, 1),
      appBar: AppBar(
        title: Text(StringName.talkAll.tr),
        backgroundColor: const Color.fromRGBO(246, 245, 248, 1),
        scrolledUnderElevation: 0,
        // actions: [
        //   IconButton(
        //     onPressed: () {},
        //     icon: ImageIcon(Assets.images.iconFilesNewDir.provider()),
        //   ),
        //   IconButton(
        //     onPressed: () {},
        //     icon: ImageIcon(Assets.images.iconMore.provider()),
        //   ),
        // ],
      ),
      body: Column(
        children: [
          // Column(
          //   children: [
          //     GestureDetector(
          //       onTap: () {
          //         Get.toNamed(RoutePath.fileSearch);
          //       },
          //       child: Container(
          //         margin: EdgeInsets.symmetric(horizontal: 12.w),
          //         padding:
          //             EdgeInsets.symmetric(horizontal: 10.w, vertical: 8.w),
          //         height: 36.w,
          //         decoration: BoxDecoration(
          //           color: Colors.white,
          //           borderRadius: BorderRadius.circular(8.w),
          //         ),
          //         child: TextField(
          //           maxLines: 1,
          //           textAlignVertical: TextAlignVertical.center,
          //           textInputAction: TextInputAction.search,
          //           decoration: InputDecoration(
          //               hintText: '搜索所有文件标题 / 内容',
          //               border: InputBorder.none,
          //               icon: ImageIcon(Assets.images.iconSearch.provider()),
          //               iconColor: const Color.fromRGBO(95, 95, 97, 1),
          //               enabled: false),
          //           style: TextStyle(fontSize: 14.sp),
          //         ),
          //       ),
          //     ),
          //   ],
          // ),
          Expanded(
              child: Padding(
            // padding: EdgeInsets.only(top: 16.w, left: 12.w, right: 12.w),
            padding: EdgeInsets.only(left: 12.w, right: 12.w),
            child: SmartRefresher(
              enablePullUp: true,
              enablePullDown: true,
              controller: controller.refreshController,
              onRefresh: controller.onRefreshData,
              onLoading: controller.onLoadMoreTalkData,
              child: CustomScrollView(
                slivers: [
                  // SliverAnimatedGrid(
                  //   itemBuilder: _buildDirItem,
                  //   gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  //     crossAxisCount: 2,
                  //     crossAxisSpacing: 8.w,
                  //     mainAxisSpacing: 8.w,
                  //     childAspectRatio: 164 / 65,
                  //   ),
                  //   initialItemCount: 10,
                  // ),
                  // SliverToBoxAdapter(
                  //   child: Padding(
                  //       padding: EdgeInsets.only(top: 20.w, bottom: 12.w),
                  //       child: Text(StringName.talkAll.tr,
                  //           style: TextStyle(
                  //               fontSize: 14.sp,
                  //               color: ColorName.secondaryTextColor,
                  //               fontWeight: FontWeight.bold))),
                  // ),
                  Obx(() {
                    return SliverList.builder(
                        itemBuilder: _buildFileItem,
                        itemCount: controller.talkList.length);
                  }),
                ],
              ),
            ),
          ))
        ],
      ),
    );
  }

  Widget _buildDirItem(
      BuildContext context, int index, Animation<double> animation) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.w),
      ),
      padding: EdgeInsets.only(left: 8.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image(
              image: Assets.images.iconFilesDir.provider(),
              width: 32.w,
              height: 32.w),
          Expanded(
              child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 8.w),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('文件夹',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: ColorName.primaryTextColor,
                        fontWeight: FontWeight.bold)),
                Text('2021-09-09 12:00:00',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: 12.sp, color: ColorName.secondaryTextColor)),
              ],
            ),
          ))
        ],
      ),
    );
  }

  Widget _buildFileItem(BuildContext context, int index) {
    TalkBean talkBean = controller.talkList[index];
    return Obx(() {
      return buildFileTalkItem(talkBean, onTap: () {
        TalkPage.start(talkBean);
      }, onLongPressStart: (details) {
        if (!accountRepository.isLogin.value) {
          return;
        }
        showTalkPopup(details.globalPosition, Alignment.bottomRight,
            onRename: () {
          showRenameTalkDialog(talkBean);
        }, onDelete: () {
          showDeleteTalkDialog(talkBean);
        });
      });
    });
  }

  void showRenameTalkDialog(TalkBean item) {
    reNameDialog(StringName.talkRenameTitle.tr, item.title.value,
        hintTxt: StringName.talkRenameTitleHint.tr,
        maxLength: 15, returnBuilder: (newName) {
      controller.requestName(newName, item);
    });
  }

  void showDeleteTalkDialog(TalkBean item) {
    talkDeleteDialog(item.id, item.title.value, returnBuilder: () {
      controller.requestDelete(item);
    });
  }
}

Widget buildFileTalkItem(TalkBean talkBean,
    {GestureTapCallback? onTap,
    GestureLongPressStartCallback? onLongPressStart}) {
  return Padding(
      padding: EdgeInsets.only(bottom: 8.w),
      child: GestureDetector(
        onLongPressStart: onLongPressStart,
        onTap: onTap,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.w),
          ),
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 14.w),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image(
                  image: (talkBean.status.value == TalkStatus.analysing ||
                          talkBean.status.value == TalkStatus.waitAnalysis)
                      ? Assets.images.iconTalkAnalysis.provider()
                      : Assets.images.iconFilesFile.provider(),
                  width: 28.w,
                  height: 32.w),
              Expanded(
                  child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(talkBean.title.value.orEmpty,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14.sp,
                            color: ColorName.primaryTextColor,
                            fontWeight: FontWeight.bold)),
                    Text(talkBean.summary.value.orEmpty,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 12.sp,
                            color:
                                talkBean.status.value == TalkStatus.analysisFail
                                    ? "#F5574E".toColor()
                                    : ColorName.secondaryTextColor)),
                    Container(
                      margin: EdgeInsets.only(top: 6.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(talkBean.duration.toFormattedDuration(),
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  color: ColorName.tertiaryTextColor)),
                          Text("  |  ",
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  color: ColorName.tertiaryTextColor,
                                  fontWeight: FontWeight.bold)),
                          Text(talkBean.createTime.orEmpty,
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  color: ColorName.tertiaryTextColor)),
                        ],
                      ),
                    )
                  ],
                ),
              )),
            ],
          ),
        ),
      ));
}
