import'package:flutter/material.dart';
import'package:line_awesome_flutter/line_awesome_flutter.dart';
import'package:provider/provider.dart';
import'package:quickcheck/model/exam_result.dart';
import'package:quickcheck/utils/ApiAdapter.dart';
import'package:quickcheck/view/Common/tab_page.dart';
import'package:quickcheck/view/TestTab/feedback_play.dart';
import'package:quickcheck/model/recent_exam.dart'asRecentExam;
import'package:quickcheck/view/feedback_tab/feedback_recommend_video.dart';
import'package:quickcheck/view/feedback_tab/feedback_tab_video.dart';
import'package:quickcheck/view/feedback_tab/visibility_provider.dart';
import'package:sizer/sizer.dart';
import'../../theme_provider.dart';
import'dart:async';
import'dart:ui';
import'package:camera/camera.dart';
import'package:flutter/cupertino.dart';
import'package:flutter/material.dart';
import'package:flutter/services.dart';
import'package:intl/intl.dart';
import'package:mccounting_text/mccounting_text.dart';
import'package:preload_page_view/preload_page_view.dart';
import'package:provider/provider.dart';
import'package:quickcheck/model/exam_result.dart';
import'package:quickcheck/model/feedbacks.dart'asfeedbacks;
import'package:quickcheck/style.dart';
import'package:quickcheck/view/TestTab/preload_player.dart';
import'package:quickcheck/view/TestTab/preload_player_chewie.dart';
import'package:quickcheck/view/feedback_tab/feedback_tab_preload.dart';
import'package:quickcheck/view/feedback_tab/feedback_tab_provider.dart';
import'package:quickcheck/view/feedback_tab/visibility_provider.dart';
import'package:sliding_up_panel/sliding_up_panel.dart';
import'package:flutter_screenutil/flutter_screenutil.dart';
import'package:video_player/video_player.dart';
import'package:sizer/sizer.dart';
import'package:miniplayer/miniplayer.dart';

classFeedbackTabPlayextendsStatefulWidget {
  @override
  _FeedbackTabPlayState createState() => _FeedbackTabPlayState();
}

//mini플레이어
// final _navigatorKey = GlobalKey();
// final ValueNotifier<double> playerExpandProgress = ValueNotifier(playerMinHeight);
//
// // ValueNotifier<bool> currentlyPlaying = ValueNotifier(null);
//
// const double playerMinHeight = 80;
// const double playerMaxHeight = 370;
// const miniplayerPercentageDeclaration = 0.1;

// ValueNotifier<double> currentlyPlaying = ValueNotifier(100.0.h);
//
// const double playerMinHeight = 70;
// const double playerMaxHeight = 370;
// const miniplayerPercentageDeclaration = 0.2;

class_FeedbackTabPlayStateextendsState<FeedbackTabPlay> {
  RecentExam.RecentExam recentExam;
  ExamResult examResult = ExamResult();
  bool _isLoading =true;
  int currentIndex = 2;
// final ExamResult _examResult;
  //
  // final int pageInt;

@override
voiddidChangeDependencies() {
super.didChangeDependencies();
    getReady();
  }

  getReady()async{
    recentExam =awaitApiAdapter.getRecentExams(size: 200, state: 'E', noAssignment:false);
    print(' _recentExam ${recentExam.results.first.id}');
    print(' _recentExam okok');
    examResult =awaitApiAdapter.getExamResult(recentExam.results.first.id);
    print(' examResult okok');
if(recentExam ==null) {
      print('empty empty empty empty empty ');
    }
if(mounted) {
      setState(() {
        _isLoading =false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
// SystemChrome.setSystemUIOverlayStyle(
    //   SystemUiOverlayStyle(statusBarColor: Colors.transparent),
    // );
return_isLoading
        ? Scaffold(
      body: Container(child: Center(child: CircularProgressIndicator(),),),
    )
        : ChangeNotifierProvider.value(
      value: FeedbackTabProvider(examResult),
      child: Material(
// debugShowCheckedModeBanner: false,
child: FeedbackTabPlayV(examResult, 0),
      ),
    );

  }
}

classFeedbackTabPlayVextendsStatefulWidget {
finalExamResult _examResult;
finalint pageInt;

  FeedbackTabPlayV(this._examResult,this.pageInt);

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

final_navigatorKey = GlobalKey();
finalValueNotifier<double> playerExpandProgress = ValueNotifier(playerMinHeight);

// ValueNotifier<bool> currentlyPlaying = ValueNotifier(null);

constdouble playerMinHeight = 80;
constdouble playerMaxHeight = 370;
constminiplayerPercentageDeclaration = 0.1;

class_FeedbackTabPlayVStateextendsState<FeedbackTabPlayV>
withSingleTickerProviderStateMixin {
  TabController _tabController;
  bool visibility =true;
  int currentIndex = 2;

  ExamResult examResult = ExamResult();
  bool _isLoading =true;

//panel
double _fabHeight;
  double _panelHeightOpen;

//TODO:닫았을때 높이
double _panelHeightClosed = 0;
finaldouble _initFabHeight = 0;

  bool isReady =false;

  @override
voidinitState() {
super.initState();
    _tabController = TabController(length: 2, vsync:this);
// getReady();
currentVisibility.addListener(() {
      print('changes');
      print('changes ${currentVisibility.visibility}');
// setState(() {
visibility = currentVisibility.visibility.value;
// });
      //   setState(() {});
});
    _fabHeight = _initFabHeight;
    examResult = widget._examResult;
if(mounted) {
      setState(() {
        _isLoading =false;
      });
    }
  }
//
  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   // getReady();
  // }

  //데이터 미리 받기
// getReady() {
  //   Future.delayed(Duration.zero, () async {
  //     context.read<FeedbackTabProvider>().init();
  //     Provider.of<FeedbackTabProvider>(context, listen: false).setPageInt(widget.pageInt);
  //   });
  // }

@override
voiddispose() {
super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
finalfeedbackModel = Provider.of<FeedbackTabProvider>(context);
    _panelHeightOpen = MediaQuery.of(context).size.height * .80;
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(statusBarColor: Colors.transparent),
    );
returnWillPopScope(
        onWillPop: ()async{
finalNavigatorState navigator = _navigatorKey.currentState;
if(!navigator.canPop())return true;
          navigator.pop();

return false;
        },
        child: Scaffold(
            body: Material(
              child: _isLoading
                  ? Container(child: Center(child: CircularProgressIndicator(),),)
                  : Scaffold(
                body:
// _isLoading
                //     ? Container(child: Center(child: CircularProgressIndicator(),),)
                //     :
Stack(
                  children: [
// tab bar view here
TabBarView(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _tabController,
                      children: [
// first tab bar view widget
FeedbackRecommendVideo(),

// second tab bar view widget
widget._examResult ==null
? Container(
                          child: Center(child: Text('아직 테스트를 완료한 기록이 없습니다'),),)
                            : Container(
                          child: FeedbackTabVideo(widget._examResult, 0),
                        ),
                      ],
                    ),
                    Positioned(
                      top: 2.5.h,
                      child: AnimatedSwitcher(
                        duration: Duration(milliseconds: 50),
                        reverseDuration: Duration(milliseconds: 200),
                        transitionBuilder: (Widget child, Animation<double> animation) {
returnFadeTransition(opacity: animation, child: child);
                        },
                        child: ValueListenableBuilder(
                            valueListenable: currentVisibility.visibility,
                            builder: (context, value, child)
                            {
returnContainer(
                                key: ValueKey(value),
                                child: value
                                    ? Container(
                                  width: 100.0.w,
                                  child: Center(
                                    child: Container(
                                      height: 5.0.h,
                                      width: 50.0.w,
                                      decoration: BoxDecoration(
                                        color: Colors.transparent,
// border: Border(right: BorderSide(color: Colors.grey[400]))
                                        // borderRadius: BorderRadius.circular(
                                        //   25.0,
                                        // ),
),
                                      child: TabBar(
                                        controller: _tabController,
// indicator: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey[400], width: 0.5.w))),
                                        // give the indicator a decoration (color and border radius)
indicator: BoxDecoration(
// borderRadius: BorderRadius.circular(
                                          //   25.0,
                                          // ),
color: Colors.transparent,
                                        ),
                                        labelColor: Colors.white,
                                        unselectedLabelColor: Colors.grey[400],
                                        labelStyle: TextStyle(fontSize: 13.0.sp, fontWeight: FontWeight.bold),//For Selected tab
unselectedLabelStyle: TextStyle(fontSize: 13.0.sp),
                                        tabs: [
// first tab [you can add an icon using the icon property]
Tab(
                                            text: '추천 영상',
                                          ),
// second tab [you can add an icon using the icon property]
Tab(
                                            text: '나의 영상',
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                )

                                    : Container(),
                              );
                            }
                        ),
                      ),
                    ),
                    Theme(
                      data: Theme.of(context).copyWith(
// canvasColor: Colors.white,
textTheme: Theme
                              .of(context)
                              .textTheme
                              .copyWith(
                              caption: TextStyle(color: Colors.black26.withOpacity(0.15)))),
                      child: ValueListenableBuilder(
                        valueListenable: playerExpandProgress,
                        builder: (BuildContext context, double height, Widget child) {
// final value = percentageFromValueInRange(
                          //     min: playerMinHeight, max: playerMaxHeight, value: height);
finalvalue = height / 100.0.h;

// var opacity = 1 - value;
                          // if (opacity < 0) opacity = 0;
                          // if (opacity > 1) opacity = 1;
returnMiniplayer(
                            controller: feedbackModel.miniplayerController,
                            onDismiss: () {
//Handle onDismissed here
},
                            valueNotifier: playerExpandProgress,
                            minHeight: 12.0.h,
                            maxHeight: 100.0.h,
                            builder: (height, percentage) {
returnContainer(
                                width: 100.0.w,
                                color: Colors.transparent,
                                child: height < 300
                                    ? Container(
// color: Colors.red,
child: Center(
                                    child: Text('hihihihihi ${playerExpandProgress.value}, ${value}', style: TextStyle(color: Colors.black),
                                    ),
                                  ),
                                )
                                    : _panel(),
                              );
                            },
                          );
                        },
                      ),

                    ),

                  ],
                ),

              ),
            ))
    );
  }

// Widget _panel(ScrollController sc) {

Widget _panel() {
finalfeedbackModel = Provider.of<FeedbackTabProvider>(context);
returnfeedbackModel.playList ==null
? Container(child: Center(child: CircularProgressIndicator(),),)
        : MediaQuery.removePadding(
        context: context,
        removeTop:true,
        child: ListView(
          physics: ClampingScrollPhysics(),
          children: <Widget>[
            SizedBox(
              height: 12.0,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: 30,
                  height: 5,
                  decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.all(Radius.circular(12.0))),
                ),
              ],
            ),
            SizedBox(
              height: 15.0,
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "챕터 ${widget._examResult.exam.chapter} 피드백 목록",
                    style: baseTextBStyle().copyWith(fontSize: 20.sp),
                  ),
                  Container(
                    height: 10,
                  ),
                  Text(
                    "총 ${feedbackModel.playList.length}단어",
                    style: regularTextStyle().copyWith(color: Colors.grey),
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 10, bottom: 10),
              color: Colors.grey[200],
              height: 10.0,
            ),
            Column(
              children: [
                ...feedbackModel.playList.asMap().entries.map((e) {
returnInkWell(
                    onTap: () {
                      print(
                          "${e.value.first.feedback.title}   :   ${e.value.first.feedback.url} : ${e.key}");
// feedbackModel.panelController.close();
currentVisibility.setVisibility(false);
                      feedbackModel.setJumpPage(e.key);
                    },
                    child: _buildWordItem(
                      e.value,
                      e.key,
                    ),
                  );
                }).toList(),
              ],
            ),
            SizedBox(
              height: 24,
            ),
          ],
        ));
  }

  Container _buildWordItem(List<feedbacks.Results> voca, int index) {
finalfeedbackModel = Provider.of<FeedbackTabProvider>(context);
returnContainer(
      margin: EdgeInsets.only(left: 10, right: 10),
      decoration:
      BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20.0))),
      child: Container(
        padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      width: 10,
                    ),
                    ClipRRect(
                      borderRadius: BorderRadius.all(
                        Radius.circular(8.0),
                      ),
                      child: Container(
                          width: 55.w,
                          height: 55.h,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: NetworkImage('${feedbackModel.panelImage[index]}',),
// image: NetworkImage('${feedbackModel.playList[index].first.feedback.thumbnail}',),
                              // image: AssetImage('assets/teacher_${(index % 4) + 1}_square.png',),
fit: BoxFit.cover,
                            ),
                          ),
                          child: Stack(
                            children: [
                              Visibility(
                                visible:
                                feedbackModel.playList[index].first.viewed,
                                child: Positioned(
                                  bottom: 0,
                                  child: Container(
                                    alignment: Alignment.center,
                                    width: 55.w / 3 * 2,
                                    height: 55.h * 0.23,
                                    color: Colors.black.withOpacity(0.6),
                                    child: Text(
                                      "학습완료",
                                      style: baseTextStyle().copyWith(
                                          color: Colors.white, fontSize: 8.sp),
                                    ),
                                  ),
                                ),
                              ),
                              ValueListenableBuilder<int>(
                                  valueListenable: feedbackModel.counterInt,
                                  builder: (context, int value, child) {
returnVisibility(
                                        visible: value == index
                                            ?true
:false,
                                        child: Container(
                                          width: 55.w,
                                          height: 55.h,
                                          child: Center(
                                            child: Icon(
                                              Icons.play_circle_fill,
                                              color: Colors.white,
                                              size: 24.sp,
                                            ),
                                          ),
                                        ));
                                  }
                              ),
                            ],
                          )),
                    ),
                  ],
                ),
                Padding(padding: EdgeInsets.only(left: 20)),
// Expanded(
Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      voca.first.feedback.vocabulary.word,
                      style: baseTextBStyle().copyWith(fontSize: 20.sp),
                      maxLines: 1,
                      overflow: TextOverflow.fade,
                    ),
                    Text(
                      "${voca.first.feedback.level}번째 피드백",
                      style: regularTextStyle(),
                    ),
                  ],
                ),
              ],
            ),
            Container(
              height: 10,
            ),
            Container(
              height: 1,
              margin: EdgeInsets.only(top: 15),
              color: Colors.grey[200],
            ),
          ],
        ),
      ),
    );
  }

}