import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:healthcare_user/common/settings.dart';
import 'package:healthcare_user/models/dynamic_code_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

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

  @override
  State<DynamicCode> createState() => _DynamicCodeState();
}

class _DynamicCodeState extends State<DynamicCode> {

  bool isDataLoading=false;
  bool isSereverIssue = false;
  List<DynamicCodeModel> originalList = [];
  List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"];
  RefreshController _refreshController =
  RefreshController(initialRefresh: true);

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

  Future<void> getAllDynamicCodes() async {
    isDataLoading=true;
    try {
      var response = await AppSettings.getDynamicCode();

      setState(() {
        originalList = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return DynamicCodeModel.fromJson(model);
        }).toList();
        originalList=originalList.reversed.toList();
        isDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  void _onRefresh() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    /*items.remove((items.length-1).toString());
    if(mounted)
      setState(() {

      });*/
    await getAllDynamicCodes();
    _refreshController.refreshCompleted(
      resetFooterState: true,
    );
  }

  void _onLoading() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    items.add((items.length+1).toString());
    if(mounted)
      setState(() {

      });
    _refreshController.loadComplete();
  }

  Widget _renderUi(){
    if(originalList.length!=0){
      return ListView.builder(
          padding:  EdgeInsets.all(0),
          itemCount: originalList.length,
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              onTap: (){

              },
              child: Card(

                //color: prescriptionsList[index].cardColor,
                child: Padding(
                  padding:EdgeInsets.all(8) ,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [

                          Container(


                            child: Row(
                              children: [
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      'Doctor Id',
                                      style: labelTextStyle(),
                                    ),
                                    SizedBox(height:MediaQuery.of(context).size.height * .01,),
                                    Text(
                                      'Dynamic code',
                                      style: labelTextStyle(),
                                    ),
                                    SizedBox(height:MediaQuery.of(context).size.height * .01,),
                                    Text(
                                      'Record Id',
                                      style: labelTextStyle(),
                                    ),

                                  ],
                                ),
                                SizedBox(width:MediaQuery.of(context).size.width * .01,),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      ':',
                                      style: labelTextStyle(),
                                    ),
                                    SizedBox(height:MediaQuery.of(context).size.height * .01,),
                                    Text(
                                      ':',
                                      style: labelTextStyle(),
                                    ),
                                    SizedBox(height:MediaQuery.of(context).size.height * .01,),
                                    Text(
                                      ':',
                                      style: labelTextStyle(),
                                    ),


                                  ],
                                ),
                                SizedBox(width:MediaQuery.of(context).size.width * .01,),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(originalList[index].doctorId.toString().toUpperCase(),style: valuesTextStyle()),
                                    SizedBox(height:MediaQuery.of(context).size.height * .01,),
                                    Text(
                                      originalList[index].dynamicCode,
                                      style: valuesTextStyle(),
                                    ),
                                    SizedBox(height:MediaQuery.of(context).size.height * .01,),
                                    Text(
                                      originalList[index].recordId,
                                      style: valuesTextStyle(),
                                    ),
                                  ],
                                ),
                              ],
                            ),




                          ),

                        ],

                      ),
                    ],
                  ),
                ),
              ),
            );
          });
    }
    else{
      return  Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * .25,),
                Text('No Dynamic Codes available'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.info,
                      color: Colors.white,
                    ),
                    onPressed: () async {

                    },
                  ),
                )
              ],
            ),
          )
      );
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Dynamic Code'),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
       /* header: WaterDropHeader(
          waterDropColor: primaryColor,
        ),*/
          header: CustomHeader(
            builder: (BuildContext context, RefreshStatus? mode) {
              return Container(
                child: Center(
                  child: CircularProgressIndicator(
                    // Set the color of the circular progress indicator
                    valueColor: AlwaysStoppedAnimation<Color>(primaryColor),
                  ),
                ),
              );
            },
          ),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus? mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("pull up load");
            }
            else if(mode==LoadStatus.loading){
              body =  Container();
            }
            else if(mode == LoadStatus.failed){
              body = Text("Load Failed!Click retry!");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("release to load more");
            }
            else{
              body = Text("No more Data");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,

        child:_renderUi()

        /*ListView.builder(
          itemBuilder: (c, i) => Card(child: Center(child: Text(items[i]))),
          itemExtent: 100.0,
          itemCount: items.length,
        ),*/
      ),
    );
  }
}
