import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/navigator.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/PackageOption_model.dart';
import 'package:mwf_app/model/package.dart';
import 'package:mwf_app/set3/offer_additional_list.dart';
import 'package:mwf_app/set4/detail_additional.dart';
import 'package:http/http.dart' as http;

class ListAdditional extends StatefulWidget {
  @override
  _ListAdditionalState createState() => _ListAdditionalState();
}

class _ListAdditionalState extends State<ListAdditional> {
  bool isLoading = false;
  Future _future;

  @override
  void initState() {
    super.initState();
    Header.routes = OfferAdditionalList();
    _future = _getData();
    //load();
  }

  loadDataPackageOption() async {
    try {
      final list =
          await PackageOption.getDataOption(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      //        await Package.getDataReadList(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final list = Package.fromJson(v);
          Package.dataReadList.add(list); // loop เก็บข้อมูล
        });
      });
    } catch (e) {
      print("Option: " + e);
    }
  }

  load() async {
    try{
      final list = await Package.getData();
      list.forEach((v) async {
        final list = Package.fromJson(v);
        Package.dataReadList.add(list);
      });
    }catch (e) {
      print(e);
    }
  }

  Future<List<Package>> _getData() async {
    try{
     final list = await Package.getData();
      list.forEach((v) async {
        final list = Package.fromJson(v);
          Package.dataReadList.add(list);
      });
    }catch(e){
      print(e);
    }
    return Package.dataReadList;
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;

    return Material(
      color: AppColors.bgColor,
      child: WillPopScope(
        onWillPop: () async {
          Get.offAll(Header.routes);
          return false;
        },
        child: Stack(
          children: <Widget>[
            Header.headerListPage(context),
            Header.mainMenu(context),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1300),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                        bottom: mediaQuery(context, 'h', 50),
                      ),
                      child: Text(
                        AppStrings.offerAdditional,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Color(0xFFB58E38),
                          fontSize: mediaQuery(context, 'h', 50),
                        ),
                      ),
                    ),
                    Container(
                      width: _width,
                      height: mediaQuery(context, 'h', 1170),
                      child: FutureBuilder(
                        future: _future,
                        builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (snapshot.data == null && 
                          snapshot.connectionState == ConnectionState.waiting || 
                          snapshot.connectionState == ConnectionState.none) {
                            return Container(
                              child: AppLoader.show(),
                            );
                        }else if(snapshot.hasError){
                            AppLoader.hide();
                            return Center(
                              child: Text("เกิดข้อผิดพลาดในการโหลดข้อมูล", 
                                style: TextStyle(fontSize: mediaQuery(context, 'h', 40)),
                            ));
                        }else if(snapshot.connectionState == ConnectionState.done){
                          AppLoader.hide();
                          return ListView.builder(
                            shrinkWrap: true,
                            addAutomaticKeepAlives: true,
                            itemCount: snapshot.data.length,
                            itemBuilder: (BuildContext context, int index) {
                              return ContentListAddition(
                                name: Package.dataReadList[index].pName,
                                packageID: Package.dataReadList[index].id,
                                detail: Package.dataReadList[index].pDetail,
                                image: Package.dataReadList[index].imageFile,
                              );
                            }
                          );
                        } else {
                          AppLoader.hide();
                          return ListView.builder(
                            shrinkWrap: true,
                            addAutomaticKeepAlives: true,
                            itemCount: snapshot.data.length,
                            itemBuilder: (BuildContext context, int index) {
                              return ContentListAddition(
                                name: Package.dataReadList[index].pName,
                                packageID: Package.dataReadList[index].id,
                                detail: Package.dataReadList[index].pDetail,
                                image: Package.dataReadList[index].imageFile,
                              );
                            },
                          );
                        }
                      },
                    ),
                    ),


                    // Container(
                    //   width: _width,
                    //   height: mediaQuery(context, 'h', 1170),
                    //   child: SingleChildScrollView(
                    //     child: Column(
                    //       children: List.generate(
                    //         Package.dataReadList.length,
                    //         (index) {
                    //           return _buildContent(
                    //             context,
                    //             Package.dataReadList[index].imageFile,
                    //             Package.dataReadList[index].pName,
                    //             Package.dataReadList[index].pDetail,
                    //             Package.dataReadList[index].id,
                    //           );
                    //         },
                    //       ),
                    //     ),
                    //   ),
                    // ),
                  ],
                ),
              
            ),
          ],
        ),
      ),
    );
  }

  _buildContent(context, image, name, detail, packageID) {
    var catchData = Image.network(
      image,
      width: mediaQuery(context, 'w', 360),
      height: mediaQuery(context, 'h', 270),
      fit: BoxFit.fill,
    );
    
    
    //image = null;
    return GestureDetector(
      onTap: () {
        AppUrl.P_Id = packageID;
        Nav.push(
          context,
          DetailAdditional(image, name, detail, packageID),
        );
      },
      child: Container(
        width: mediaQuery(context, 'w', 1005),
        padding: EdgeInsets.all(
          mediaQuery(context, 'h', 40),
        ),
        margin: EdgeInsets.only(
          bottom: mediaQuery(context, 'h', 40),
        ),
        decoration: BoxDecoration(
          borderRadius: new BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 20),
            ),
          ),
          boxShadow: [
            appShadow(),
          ],
          color: Colors.white,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            image != null
                ? CachedNetworkImage(
                  useOldImageOnUrlChange: true,
                  imageUrl: image,
                  width: mediaQuery(context, 'w', 360),
                  placeholder: (context, url) => Center(child: CircularProgressIndicator()),
                  errorWidget: (context, url, error) =>  Icon(Icons.error),
                )
                : Image.asset(
                    AppAssets.noimage,
                    width: mediaQuery(context, 'w', 360),
                    height: mediaQuery(context, 'h', 270),
                    fit: BoxFit.cover,
                  ),
            SizedBox(
              width: mediaQuery(context, 'w', 40),
            ),
            Flexible(
              child: Text(
                name != null ? name : '',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
} //class


class ContentListAddition extends StatefulWidget {
  ContentListAddition({
    this.image, this.name, this.detail, this.packageID
  });

  final String image;
  final String name;
  final String detail;
  final String packageID;
  

  @override
  _ContentListAdditionState createState() => _ContentListAdditionState(
    this.image, this.name, this.detail, this.packageID
  );
}

class _ContentListAdditionState extends State<ContentListAddition>
with  AutomaticKeepAliveClientMixin<ContentListAddition> {
  _ContentListAdditionState(
    this.image, this.name, this.detail, this.packageID
  );

  final String image;
  final String name;
  final String detail;
  final String packageID;


  @override
  Widget build(BuildContext context) {
    super.build(context);
    var catchData = Image.network(
      image,
      width: mediaQuery(context, 'w', 360),
      height: mediaQuery(context, 'h', 270),
      fit: BoxFit.fill,
    );
    //image = null;
    return GestureDetector(
      onTap: () {
        AppUrl.P_Id = packageID;
        Nav.push(
          context,
          DetailAdditional(image, name, detail, packageID),
        );
      },
      child: Container(
        width: mediaQuery(context, 'w', 1005),
        padding: EdgeInsets.all(
          mediaQuery(context, 'h', 40),
        ),
        margin: EdgeInsets.only(
          bottom: mediaQuery(context, 'h', 40),
        ),
        decoration: BoxDecoration(
          borderRadius: new BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 20),
            ),
          ),
          boxShadow: [
            appShadow(),
          ],
          color: Colors.white,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            image != null
                ? CachedNetworkImage(
                  useOldImageOnUrlChange: true,
                  imageUrl: image,
                  width: mediaQuery(context, 'w', 360),
                  placeholder: (context, url) => Center(child: CircularProgressIndicator()),
                  errorWidget: (context, url, error) =>  Icon(Icons.error),
                )
                : Image.asset(
                    AppAssets.noimage,
                    width: mediaQuery(context, 'w', 360),
                    height: mediaQuery(context, 'h', 270),
                    fit: BoxFit.cover,
                  ),
            SizedBox(
              width: mediaQuery(context, 'w', 40),
            ),
            Flexible(
              child: Text(
                name != null ? name : '',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}