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/video_response.dart';
import 'package:e_commerce_training/src/page/videos/video_cubit.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:e_commerce_training/src/widget/video_widget.dart';
import 'package:easy_localization/easy_localization.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:optimized_cached_image/optimized_cached_image.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';

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

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

class _VideoPageState extends State<VideoPage>
    with AutomaticKeepAliveClientMixin<VideoPage>, SingleTickerProviderStateMixin {
  late VideoCubit _cubit;
  TabController? _tabController;
  List<RefreshController> listController = [];
  int index = 0;
  late YoutubePlayerController _controller;

  @override
  bool get wantKeepAlive => false;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(context, R.string.video.tr(), rightIcons: [MdiIcons.cartOutline]),
      body: BlocProvider(
        create: (BuildContext context) => _cubit,
        child: BlocConsumer<VideoCubit, VideoState>(
          listener: (context, state) {
            if (state is VideoFailure) Util.showErrorSnackBar(context, state.error);
            if (!(state is VideoLoading)) {
              listController.forEach((element) {
                element.refreshCompleted();
                element.loadComplete();
              });
            }
            if (state is GetListVideoSuccess) {
              if (_tabController == null) {
                _tabController = TabController(length: _cubit.listCatalogVideo.length, vsync: this);
                _tabController!.addListener(() {
                  _cubit.onChangeIndex(_tabController!.index);
                });
                listController = List.generate(_cubit.listCatalogVideo.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.listCatalogVideo
                          .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: List.generate(_cubit.listVideo.length, (index) => pageBlog(index)),
                ),
              ),
            ],
          );
  }

  Widget pageBlog(int index) {
    List<VideoData> listBlog = _cubit.listVideo[index];
    return SmartRefresher(
      controller: listController[index],
      enablePullUp: true,
      onRefresh: () => _cubit.getListVideo(index, isRefresh: true),
      onLoading: () => _cubit.getListVideo(index, isLoadMore: true),
      child: ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        shrinkWrap: true,
        itemCount: listBlog.length,
        itemBuilder: (BuildContext context, int index) {
          VideoData data = listBlog[index];
          return Container(
            margin: EdgeInsets.only(bottom: 10),
            width: double.infinity,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(10), color: R.color.grey100),
            //padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
            child: InkWell(
              onTap: () {
                Util.navigatePage(
                    context,
                    VideoWidget(
                      videoId: data.youtubeVideoId ?? "",
                    ));
              },
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Stack(
                    children: [
                      Container(
                        width: 100.h,
                        height: 100.h,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: OptimizedCacheImageProvider(data.thumb ?? ""),
                            fit: BoxFit.fill,
                          ),
                          borderRadius:
                              BorderRadius.only(topLeft: Radius.circular(10), bottomLeft: Radius.circular(10)),
                        ),
                      ),
                      Positioned(
                        top: 0,
                        bottom: 0,
                        left: 0,
                        right: 0,
                        child: Icon(
                          MdiIcons.playCircleOutline,
                          color: R.color.white,
                          size: 30.h,
                        ),
                      )
                    ],
                  ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      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.createDate, Const.DATE_FORMAT_POST) ?? "",
                                style: TextStyle(fontSize: 16.sp, color: R.color.black.withOpacity(0.7)),
                              ),
                              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();
  }
}
