import 'package:PiliPlus/common/widgets/reorder_mixin.dart';
import 'package:PiliPlus/http/fav.dart';
import 'package:PiliPlus/http/loading_state.dart';
import 'package:PiliPlus/models_new/fav/fav_folder/list.dart';
import 'package:PiliPlus/pages/fav/video/controller.dart';
import 'package:PiliPlus/pages/fav/video/widgets/item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

class FavFolderSortPage extends StatefulWidget {
  const FavFolderSortPage({super.key, required this.favController});

  final FavController favController;

  @override
  State<FavFolderSortPage> createState() => _FavFolderSortPageState();
}

class _FavFolderSortPageState extends State<FavFolderSortPage>
    with ReorderMixin {
  FavController get _favController => widget.favController;

  late List<FavFolderInfo> sortList = List<FavFolderInfo>.from(
    _favController.loadingState.value.data!,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('收藏夹排序'),
        actions: [
          TextButton(
            onPressed: () async {
              final res = await FavHttp.sortFavFolder(
                sort: sortList.map((item) => item.id).join(','),
              );
              if (res.isSuccess) {
                SmartDialog.showToast('排序完成');
                _favController.loadingState.value = Success(sortList);
                if (mounted) {
                  Get.back();
                }
              } else {
                res.toast();
              }
            },
            child: const Text('完成'),
          ),
          const SizedBox(width: 16),
        ],
      ),
      body: _buildBody,
    );
  }

  void onReorderItem(int oldIndex, int newIndex) {
    if (oldIndex == 0 || newIndex == 0) {
      SmartDialog.showToast('默认收藏夹不支持排序');
      return;
    }

    sortList.insert(newIndex, sortList.removeAt(oldIndex));

    setState(() {});
  }

  Widget get _buildBody {
    return ReorderableListView.builder(
      onReorderItem: onReorderItem,
      proxyDecorator: proxyDecorator,
      physics: const AlwaysScrollableScrollPhysics(),
      itemCount: sortList.length,
      padding:
          MediaQuery.viewPaddingOf(context).copyWith(top: 0) +
          const EdgeInsets.only(bottom: 100),
      itemBuilder: (context, index) {
        final item = sortList[index];
        final key = item.id.toString();
        return SizedBox(
          key: Key(key),
          height: 98,
          child: FavVideoItem(
            heroTag: key,
            item: item,
            onLongPress: index == 0
                ? () => SmartDialog.showToast('默认收藏夹不支持排序')
                : null,
          ),
        );
      },
    );
  }
}
