import 'package:flutter/material.dart';
import 'package:animations/animations.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import 'notificacao.dart';
import 'notificacoes_controller.dart';
//import 'package:supercharged/supercharged.dart';

class NotificacoesScreen extends StatelessWidget {
  final NotificacoesController c = Get.put(NotificacoesController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Notificações'),
        leading: Container(),
        leadingWidth: 0,
        centerTitle: false,
      ),
      body: Obx(() => c.loading.value ? Center(child: CircularProgressIndicator(),) : c.errorCode.value != 0 ? this._buildError() : RefreshIndicator(
        onRefresh: c.refresh,
        // child: AnimatedList(
        //   key: c.listKey,
        //   padding: const EdgeInsets.all(8.0),
        //   initialItemCount: c.notificacoesResults.length + 1,
        //   itemBuilder: (context,index,animation){
        //     if (index < c.notificacoesResults.length) {
        //       return SlideTransition(
        //         //position: c.animation,
        //         position: Tween<Offset>(
        //           begin: const Offset(-1, 0),
        //           end: Offset(0, 0),
        //         ).animate(animation),
        //         child: this._buildListTile(index)
        //       );
        //     } else if (index > 1) {
        //       if(c.loadMore == null || c.loadMore){
        //         c.getNotificacoesBloc();
        //         return Container(
        //           height: 40,
        //           width: 40,
        //           alignment: Alignment.center,
        //           child: CircularProgressIndicator(),
        //         ); 
        //       }
        //       else{
        //         return Center(child: Padding(
        //           padding: const EdgeInsets.only(top: 8.0),
        //           child: Text("Não há mais Notificações para exibir."),
        //         ),);                      
        //       }                   
        //     } 
        //     else {
        //       return Center(child: Padding(
        //         padding: const EdgeInsets.only(top: 8.0),
        //         child: Text("Não há mais Notificações para exibir."),
        //       ),);
        //     }  
        //   }
        // ),
        child: ListView.builder(
          padding: const EdgeInsets.all(8.0),
          itemCount: c.notificacoesResults.length + 1,
          itemBuilder: (_,index){
            if (index < c.notificacoesResults.length) {
              return this._buildListTile(index);
              // return SlideTransition(
              //   position: c.animation,
              //   child: this._buildListTile(index)
              // );
            } else if (index > 1) {
              if(c.loadMore){
                c.getNotificacoesBloc();
                return Container(
                  height: 40,
                  width: 40,
                  alignment: Alignment.center,
                  child: CircularProgressIndicator(),
                ); 
              }
              else{
                return Center(child: Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text("Não há mais Notificações para exibir."),
                ),);                      
              }                   
            } 
            else {
              return Center(child: Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: Text("Não há mais Notificações para exibir."),
              ),);
            }          
          },
        ),
      )),
      // body: ListView(
      //   padding: const EdgeInsets.all(8.0),
      //   children: <Widget>[
      //     ...List<Widget>.generate(10, (int index) {
      //       return this._buildListTile(index);
      //     }),
      //   ],
      // ),
    );
  }

  Widget _buildError(){
    return Center(
      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'),)
        ],
      ),
    );
  }

  Widget _buildListTile(int index) {
    if(c.notificacoesResults[index].tipoConteudo == 'L'){
      return this._buildListTileTile(index: index,onTap: (){
        c.notificacaoLidaBloc(c.notificacoesResults[index].iD).then((value) => launch(c.notificacoesResults[index].conteudo!));        
      });
    }
    return OpenContainer<bool>(
      //openColor: Colors.transparent,
      closedColor: Get.theme.primaryColor.withOpacity(0.2),
      transitionType: ContainerTransitionType.fadeThrough,
      openBuilder: (BuildContext _, VoidCallback openContainer) {
        c.notificacoesResults[index].visualizado = true;
        c.getNotificacaoDetail(c.notificacoesResults[index].iD);  
        //return _DetailsPage();
        return NotificacaoDetail();        
      },
      onClosed: (bool? isMarkedAsDone) {
        c.notificacaoLidaBloc(c.notificacoesResults[index].iD);
        if (isMarkedAsDone ?? false)
          Get.rawSnackbar(message: 'Marked as done!');
      },
      tappable: false,
      closedShape: const RoundedRectangleBorder(),
      closedElevation: 0.0,
      closedBuilder: (BuildContext _, VoidCallback openContainer) {
        return this._buildListTileTile(index: index,onTap: openContainer);
      },
    );
  }

  Widget _buildListTileTile({Function? onTap,required int index}){
    return ListTile(
      leading: CircleAvatar(
        backgroundImage: (GetUtils.isNullOrBlank(c.notificacoesResults[index].imageUrl)! ? AssetImage(
          'assets/images/logo.png',
        ) : NetworkImage(c.notificacoesResults[index].imageUrl!)) as ImageProvider<Object>?,
        // child: Image.asset(
        //   'assets/images/logo.png',
        //   width: 40,
        // ),
      ),
      onTap: onTap as void Function()?,
      trailing: c.notificacoesResults[index].visualizado! ? Text('') : Text('●',style: TextStyle(color: Colors.blue),),
      title: Text(c.notificacoesResults[index].titulo!),
      subtitle: Text(c.getDateFormatada(c.notificacoesResults[index].dataNotificacao!)),
    );    
  }
}