import 'package:cached_network_image/cached_network_image.dart';
import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/blog_response.dart';
import 'package:e_commerce_training/src/page/blogs/blog_cubit.dart';
import 'package:e_commerce_training/src/page/webview_page/webview_page.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/date_util.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/widget/custom_appbar.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BlogPage extends StatefulWidget {
  const BlogPage({Key? key}) : super(key: key);

  @override
  _BlogPageState createState() => _BlogPageState();
}

class _BlogPageState extends State<BlogPage>
    with AutomaticKeepAliveClientMixin<BlogPage>, SingleTickerProviderStateMixin {
  late BlogCubit _cubit;
  TabController? _tabController;
  List<RefreshController> listController = [];
  int index = 0;

  @override
  bool get wantKeepAlive => false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    AppRepository repository = AppRepository();
    _cubit = BlogCubit(repository);
    _cubit.getCatalogBlog();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(
        context,
        R.string.news.tr(),
        rightIcons: [MdiIcons.cartOutline],
      ),
      body: BlocProvider(
        create: (BuildContext context) => _cubit,
        child: BlocConsumer<BlogCubit, BlogState>(
          listener: (context, state) {
            if (state is BlogFailure) Util.showErrorSnackBar(context, state.error);
            if (!(state is BlogLoading)) {
              listController.forEach((element) {
                element.refreshCompleted();
                element.loadComplete();
              });
            }
            if (state is GetListCatalogSuccess) {
              if (_tabController == null) {
                _tabController = TabController(length: _cubit.listCatalogBlog.length, vsync: this);
                _tabController!.addListener(() {
                  _cubit.onChangeIndex(_tabController!.index);
                });
                listController = List.generate(_cubit.listCatalogBlog.length, (index) => RefreshController());
              }
            }
          },
          builder: (context, state) {
            return buildBody();
          },
        ),
      ),
    );
  }

  Widget buildBody() {
    return _tabController == null
        ? Container()
        : Column(
            children: [
              Container(
                color: R.color.white,
                child: Stack(
                  fit: StackFit.passthrough,
                  alignment: Alignment.bottomLeft,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(color: Theme.of(context).dividerColor, width: 1),
                        ),
                      ),
                    ),
                    TabBar(
                      controller: _tabController,
                      unselectedLabelColor: R.color.black,
                      labelColor: R.color.primaryColor,
                      isScrollable: true,
                      indicatorColor: R.color.primaryColor,
                      tabs: _cubit.listCatalogBlog
                          .map((e) => Container(
                                padding: EdgeInsets.symmetric(vertical: 10),
                                child: Text(
                                  e.catalogName ?? "",
                                  style: TextStyle(fontSize: 16.sp, color: R.color.primaryColor),
                                ),
                              ))
                          .toList(),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: TabBarView(
                  controller: _tabController,
                  children:
                      //_cubit.listBlog.map((e) => pageBlog(index)).toList()
                      List.generate(_cubit.listBlog.length, (index) => pageBlog(index)),
                ),
              ),
            ],
          );
  }

  Widget pageBlog(int index) {
    List<BlogData> listBlog = _cubit.listBlog[index];
    return SmartRefresher(
      controller: listController[index],
      enablePullUp: true,
      onRefresh: () => _cubit.getListBlog(index, isRefresh: true),
      onLoading: () => _cubit.getListBlog(index, isLoadMore: true),
      child: ListView.separated(
        shrinkWrap: true,
        itemCount: listBlog.length,
        padding: EdgeInsets.symmetric(vertical: 10),
        separatorBuilder: (BuildContext context, int index) {
          return Container(
            padding: EdgeInsets.symmetric(vertical: 10),
            color: R.color.grey,
          );
        },
        itemBuilder: (BuildContext context, int index) {
          BlogData data = listBlog[index];
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: InkWell(
              onTap: data.vietnameseSlug == null
                  ? null
                  : () {
                      Util.navigatePage(
                        context,
                        WebviewPage(
                          title: data.vietnameseName ?? "",
                          url: data.vietnameseSlug,
                        ),
                      );
                    },
              child: Row(
                children: [
                  CachedNetworkImage(
                    imageUrl: Util.getImageUrl(data.image ?? "", host: "https://zing.vn/") ?? "",
                    height: 70.h,
                    width: 70.h,
                    fit: BoxFit.fill,
                  ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            data.vietnameseName ?? "",
                            maxLines: 2,
                            style: TextStyle(fontSize: 16.sp),
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(
                            height: 5,
                          ),
                          Row(
                            children: [
                              Text(R.string.poster.tr(), style: TextStyle(fontSize: 16.sp, color: R.color.grey500)),
                              SizedBox(
                                width: 5,
                              ),
                              Text(data.createName ?? "", style: TextStyle(fontSize: 16.sp, color: R.color.black)),
                            ],
                          ),
                          SizedBox(
                            height: 5,
                          ),
                          Row(
                            children: [
                              Text(
                                DateUtil.parseDateDefault(data.publishDate, Const.DATE_FORMAT_POST) ?? "",
                                style: TextStyle(fontSize: 16.sp),
                              ),
                              SizedBox(
                                width: 5,
                              ),
                              InkWell(
                                onTap: () {},
                                child: Text(
                                  data.catalogName ?? "",
                                  style: TextStyle(fontSize: 16.sp, color: R.color.primaryColor),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _tabController!.removeListener(() {});
    super.dispose();
  }
}
