import 'package:modelo/videos/youtube_video_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get/get.dart';
import 'package:transparent_image/transparent_image.dart';

//import 'players/YoutubeCustomWidget.dart';
import 'api/youtube_classes.dart';
import 'bloc/youtube_controller.dart';
//import 'players/YoutubeDefaultWidget.dart';

// class YouTubeVideosScreen extends StatelessWidget {
//   final YouTubeController c = Get.put(YouTubeController());

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text('Vídeos'),
//       ),
//       body: Obx(() => c.loading.value ? Center(child: CircularProgressIndicator(),) : c.errorCode.value != 0 ? this._buildError() : RefreshIndicator(
//         onRefresh: c.refresh,
//         child: AnimationLimiter(
//           child: ListView.builder(
//             padding: const EdgeInsets.all(8.0),
//             itemCount: c.itens.length + 1,
//             itemBuilder: (_,index){
//               if (index < c.itens.length) {
//               var item = c.itens[index];
//               return AnimationConfiguration.staggeredList(
//                 position: index,
//                 duration: const Duration(milliseconds: 375),
//                 child: SlideAnimation(
//                     verticalOffset: 30.0,
//                     child: FadeInAnimation(
//                       child: listItem(item),
//                     )
//                   )
//                 );
//                 // return SlideTransition(
//                 //   position: c.animation,
//                 //   child: this._buildListTile(index)
//                 // );
//               } else if (index > 1) {
//                 if (!GetUtils.isNullOrBlank(c.results.value.nextPageToken)) {
//                   c.getChannelVideosBloc();
//                   return Center(child: CircularProgressIndicator(),);
//                 } else {
//                   return Center(
//                     child: Padding(
//                       padding: const EdgeInsets.only(top: 8.0,bottom: 25.0),
//                       child:
//                           Text("Não há mais Vídeos para exibir."),
//                     ),
//                   );
//                 }
//               }
//               else {
//                 return Center(child: Padding(
//                   padding: const EdgeInsets.only(top: 8.0),
//                   child: Text("Não há mais Vídeos para exibir."),
//                 ),);
//               }
//             },
//           ),
//         ),
//       )),
//     );
//   }

//   Widget listItem(YouTubeItems item) {
//     return InkWell(
//       onTap: (){
//         showModalBottomSheet(context: Get.context, builder: (_)=>Container(
//           child: Column(
//             children: [
//               ListTile(
//                 title: Text('Player 1'),
//                 onTap: (){
//                   Get.to(() => YouTubeVideoPlayerScreen(ytVideo: item,));
//                 },
//               ),
//               // ListTile(
//               //   title: Text('Player 2 - YoutubeDefaultWidget'),
//               //   onTap: (){
//               //     Navigator.of(context).push(MaterialPageRoute(builder: (_)=>YoutubeDefaultWidget(id: item.id.videoId)));
//               //   },
//               // ),
//               // ListTile(
//               //   title: Text('Player 3 - YoutubeCustomWidget'),
//               //   onTap: (){
//               //     Navigator.of(context).push(MaterialPageRoute(builder: (_)=>YoutubeCustomWidget()));
//               //   },
//               // ),
//               // ListTile(
//               //   title: Text('Player 3 - API key'),
//               //   onTap: (){
//               //     FlutterYoutube.playYoutubeVideoById(
//               //       apiKey:FuncoesGerais.youtubeApiKey,
//               //       videoId: item.id.videoId,
//               //       autoPlay: true, //default falase
//               //       fullScreen: true //default false
//               //     );
//               //   },
//               // )
//             ],
//           ),
//         ));
//       },
//       child: Card(
//         elevation: 0,
//         color: Colors.transparent,
//         child: Container(
//           //margin: EdgeInsets.only(bottom: 8.0),
//           child: Row(
//             children: <Widget>[
//               LimitedBox(
//                 maxHeight: 100.0,
//                 child: AspectRatio(
//                   aspectRatio: 4/3,
//                   child: FadeInImage.memoryNetwork(
//                     placeholder: kTransparentImage,
//                     image: item.snippet?.thumbnails?.thumbDefault?.url ?? '',
//                     fit: BoxFit.cover,
//                   ),
//                 ),
//               ),
//               Padding(padding: EdgeInsets.only(right: 10.0)),
//               Expanded(
//                   child: Column(
//                       mainAxisAlignment: MainAxisAlignment.start,
//                       crossAxisAlignment: CrossAxisAlignment.start,
//                       children: <Widget>[
//                     Text(
//                       item.snippet.title,
//                       softWrap: true,
//                       maxLines: 2,
//                       style: TextStyle(fontSize: 13.0,fontWeight: FontWeight.bold),
//                     ),
//                     Padding(padding: EdgeInsets.only(bottom: 1.5)),
//                     Text(
//                       item.snippet.description,
//                       softWrap: true,
//                       maxLines: 3,
//                       style: TextStyle(fontSize: 11.0,fontWeight: FontWeight.w400),
//                     ),
//                     Padding(padding: EdgeInsets.only(bottom: 3.0)),
//                     Text(
//                       item.snippet.publishedAt,
//                       softWrap: true,
//                       maxLines: 1,
//                       style: TextStyle(fontSize: 9.0,fontWeight: FontWeight.w300),
//                     ),
//                   ]))
//             ],
//           ),
//         ),
//       ),
//     );
//   }

//   Widget _buildError(){
//     return Column(
//       mainAxisAlignment: MainAxisAlignment.center,
//       crossAxisAlignment: CrossAxisAlignment.center,
//       children: [
//         Text(c.errorMessage),
//         RaisedButton(onPressed: c.refresh, child: Text('Atualizar'),)
//       ],
//     );
//   }
// }

class YouTubeVideosScreen extends StatefulWidget {
  @override
  _YouTubeVideosScreenState createState() => _YouTubeVideosScreenState();
}

class _YouTubeVideosScreenState extends State<YouTubeVideosScreen>
    with AutomaticKeepAliveClientMixin<YouTubeVideosScreen> {
  final YouTubeController c = Get.put(YouTubeController());

  @override
  void initState() {
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Vídeos'),
      ),
      body: Obx(() => c.loading.value
          ? Center(
              child: CircularProgressIndicator(),
            )
          : c.errorCode.value != 0
              ? this._buildError()
              : RefreshIndicator(
                  onRefresh: c.refresh,
                  child: AnimationLimiter(
                    child: ListView.builder(
                      padding: const EdgeInsets.all(8.0),
                      itemCount: c.itens.length + 1,
                      itemBuilder: (_, index) {
                        if (index < c.itens.length) {
                          var item = c.itens[index];
                          return AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 375),
                              child: SlideAnimation(
                                  verticalOffset: 30.0,
                                  child: FadeInAnimation(
                                    child: listItem(item),
                                  )));
                          // return SlideTransition(
                          //   position: c.animation,
                          //   child: this._buildListTile(index)
                          // );
                        } else if (index > 1) {
                          if (!GetUtils.isNullOrBlank(
                              c.results.value.nextPageToken)!) {
                            c.getChannelVideosBloc();
                            return Center(
                              child: CircularProgressIndicator(),
                            );
                          } else {
                            return Center(
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 8.0, bottom: 25.0),
                                child: Text("Não há mais Vídeos para exibir."),
                              ),
                            );
                          }
                        } else {
                          return Center(
                            child: Padding(
                              padding: const EdgeInsets.only(top: 8.0),
                              child: Text("Não há mais Vídeos para exibir."),
                            ),
                          );
                        }
                      },
                    ),
                  ),
                )),
    );
  }

  Widget listItem(YouTubeItems item) {
    return InkWell(
      onTap: () {
        if (GetUtils.isNullOrBlank(item.id!.videoId)!) {
          Get.rawSnackbar(message: 'Não foi possível reproduzir o vídeo');
        } else {
          Get.to(() => YouTubeVideoPlayerScreen(
                ytVideo: item,
              ));
        }
      },
      child: Card(
        elevation: 0,
        color: Colors.transparent,
        child: Container(
          //margin: EdgeInsets.only(bottom: 8.0),
          child: Row(
            children: <Widget>[
              LimitedBox(
                maxHeight: 100.0,
                child: AspectRatio(
                  aspectRatio: 4 / 3,
                  child: FadeInImage.memoryNetwork(
                    placeholder: kTransparentImage,
                    image: item.snippet?.thumbnails?.thumbDefault?.url ?? '',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Padding(padding: EdgeInsets.only(right: 10.0)),
              Expanded(
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                    Text(
                      item.snippet!.title!,
                      softWrap: true,
                      maxLines: 2,
                      style: TextStyle(
                          fontSize: 13.0, fontWeight: FontWeight.bold),
                    ),
                    Padding(padding: EdgeInsets.only(bottom: 1.5)),
                    Text(
                      item.snippet!.description!,
                      softWrap: true,
                      maxLines: 3,
                      style: TextStyle(
                          fontSize: 11.0, fontWeight: FontWeight.w400),
                    ),
                    Padding(padding: EdgeInsets.only(bottom: 3.0)),
                    Text(
                      c.getDateFormatada(item.snippet!.publishedAt!),
                      softWrap: true,
                      maxLines: 1,
                      style:
                          TextStyle(fontSize: 9.0, fontWeight: FontWeight.w300),
                    ),
                  ]))
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildError() {
    return Container(
      width: double.maxFinite,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(c.errorMessage!),
          ElevatedButton(onPressed: c.refresh, child: Text('Atualizar'))
          //RaisedButton(onPressed: c.refresh, child: Text('Atualizar'),)
        ],
      ),
    );
  }
}
