import 'dart:convert';
import 'dart:io';
import 'package:flutter_svg/flutter_svg.dart';import 'package:flutter/material.dart';

import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:watermanagement/models/connected_customers_model.dart';
import 'package:watermanagement/models/pending_suppliers_model.dart';
import 'package:watermanagement/settings.dart';
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:location/location.dart' as locationmap;
import 'google_maps_place_picker_mb/src/models/pick_result.dart';
import 'google_maps_place_picker_mb/src/place_picker.dart';
import 'package:watermanagement/google_maps_place_picker_mb/google_maps_place_picker.dart';
import 'package:watermanagement/keys.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  State<ConectedPendingCustomers> createState() => _ConectedPendingCustomersState();
}

class _ConectedPendingCustomersState extends State<ConectedPendingCustomers> with TickerProviderStateMixin {
  bool isSupplierDataLoading=false;
  bool isSereverIssue = false;
  bool isSereverIssueConnected = false;
  bool isSereverIssuePending = false;

  List<ConnectedCustomersModel> connectedCustomersList = [];
  List<PendingSuppliersModel> pendingSuppliersList = [];


  late TabController _controller;
  bool isConnectedDataLoading=false;
  bool isPendingDataLoading=false;



  final List<Tab> topTabs = <Tab>[
    Tab(
      child: Column(
        children: [Text('Pending Customers')],
      ),
    ),
     Tab(
      child: Column(
        children: [Text('Conected Customers')],
      ),
    ),

  ];



  Future<void> getConnectedSuppliersData() async {
    isConnectedDataLoading = true;

    try {
      var response = await AppSettings.getConnectedCustomers();

      setState(() {
        connectedCustomersList =
            ((jsonDecode(response)['data']) as List).map((dynamic model) {
              return ConnectedCustomersModel.fromJson(model);
            }).toList();
        isConnectedDataLoading = false;
      });


    } catch (e) {
      setState(() {
        isConnectedDataLoading = false;
        isSereverIssuePending = true;
      });
    }
  }


  Future<void> getPendingSuppliersData() async {
    isPendingDataLoading = true;

    try {
      var response = await AppSettings.getPendingSuppliers();

      setState(() {
        pendingSuppliersList =
            ((jsonDecode(response)['data']) as List).map((dynamic model) {
              return PendingSuppliersModel.fromJson(model);
            }).toList();
        isPendingDataLoading = false;
      });


    } catch (e) {
      setState(() {
        isPendingDataLoading = false;
        isSereverIssuePending = true;
      });
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    _controller = TabController(vsync: this, length: 2);
    getConnectedSuppliersData();
    getPendingSuppliersData();
    super.initState();
  }

  Widget connectedCustomers(){
    if(connectedCustomersList.length!=0){

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: connectedCustomersList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Padding(
                      padding:EdgeInsets.all(8) ,
                      child: Container(
                        //width: MediaQuery.of(context).size.width * .50,
                          child: Row(
                            children: [
                             /* Column(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('username :',
                                      style: labelTextStyle()),

                                  SizedBox(height: 10,),
                                  Text('phone:',
                                      style: labelTextStyle()),
                                  SizedBox(height: 10,),
                                  Text('buildingname:',
                                      style: labelTextStyle()),
                                  SizedBox(height: 10,),
                                  Text('address:',
                                      style: labelTextStyle()),
                                ],
                              ),
                              SizedBox(width: 10,),*/
                              Expanded(child:Column(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                               /* children: [
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_name
                                          .toUpperCase(),
                                      style: valuesTextStyle()),
                                  SizedBox(height: 10,),
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_phone_number
                                          .toUpperCase(),
                                      style: valuesTextStyle()),
                                  SizedBox(height: 10,),
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_building_name
                                          .toUpperCase(),
                                      style: valuesTextStyle()),
                                  SizedBox(height: 10,),
                                  Text(maxLines:3,
                                      connectedCustomersList[index]
                                          .customer_address
                                          .toUpperCase(),
                                      style: valuesTextStyle())
                                ],*/
                                children: [
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_name
                                          .toUpperCase(),
                                      style: valuesTextStyle()),
                                  SizedBox(height: 10,),
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_phone_number
                                          .toUpperCase(),
                                      style: valuesTextStyle()),
                                  SizedBox(height: 10,),
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_building_name
                                          .toUpperCase(),
                                      style: valuesTextStyle()),
                                  SizedBox(height: 10,),
                                  Text(
                                      connectedCustomersList[index]
                                          .customer_address
                                          .toUpperCase(),
                                      style: valuesTextStyle())
                                ],
                              ),),
                              Column(
                                children: [
                                  IconButton(
                                    iconSize: 30,
                                    icon: const Icon(
                                      Icons.phone,
                                      color: primaryColor,
                                    ),
                                    onPressed: () async {
                                      final Uri _phoneUri = Uri(
                                          scheme: "tel",
                                          path: connectedCustomersList[index]
                                              .customer_phone_number);
                                      try {
                                        await launch(
                                            _phoneUri.toString());
                                      } catch (error) {
                                        throw ("Cannot dial");
                                      }
                                    },
                                  ),
                                  Text(
                                    'Call now',
                                    style: iconBelowTextStyle(),
                                  ),
                                ],
                              ),

                            ],

                          )
                      ),
                    ),
                  );
                }) ),
          ]);
    }
    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 Data Found'),
                SizedBox(
                  height: 20,
                ),

              ],
            ),
          )
      );
    }
  }

  Widget pendingCustomers(){
    if(pendingSuppliersList.length!=0){
      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: pendingSuppliersList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Padding(
                      padding:EdgeInsets.all(8) ,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                              width: MediaQuery.of(context).size.width * .50,
                              child: Row(
                                children: [
                                 /* Column(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text('username :',
                                          style: labelTextStyle()),

                                      SizedBox(height: 10,),
                                      Text('contactNumber:',
                                          style: labelTextStyle()),
                                      SizedBox(height: 10,),
                                      Text('address:',
                                          style: labelTextStyle()),
                                    ],
                                  ),
                                  SizedBox(width: 10,),*/
                                  Expanded(child:Column(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                          pendingSuppliersList[index]
                                              .customer_name
                                              .toUpperCase(),
                                          style: valuesTextStyle()),
                                      SizedBox(height: 10,),
                                      Text(
                                          pendingSuppliersList[index]
                                              .customer_phone_number
                                              .toUpperCase(),
                                          style: valuesTextStyle()),
                                      SizedBox(height: 10,),
                                      Text(
                                          pendingSuppliersList[index]
                                              .customer_address
                                              .toUpperCase(),
                                          style: valuesTextStyle())
                                    ],
                                  ),)
                                ],
                              )
                          ),

                          TextButton(
                            child:  Text(
                              'Accept',
                              style: TextStyle(fontSize: 15,
                                  color:primaryColor/*FilteredList[index].text_color*/ ),
                            ),
                            onPressed: () async{
                              var payload = new Map<String, dynamic>();
                              payload["supplierId"] =AppSettings.supplierId;
                              payload["customerId"] = pendingSuppliersList[index].customer_id;
                              bool requestStatus = await AppSettings.acceptRequest(payload);

                              if(requestStatus){
                                AppSettings.longSuccessToast("Request Accepted Successfully");

                                await getPendingSuppliersData();
                                await getConnectedSuppliersData();

                              }
                              else{
                              }

                            },
                          ),

                          TextButton(
                            child:  Text(
                              'Reject',
                              style: TextStyle(fontSize: 15,
                                  color:primaryColor/*FilteredList[index].text_color*/ ),
                            ),
                            onPressed: () async{
                              var payload = new Map<String, dynamic>();
                              payload["supplierId"] =AppSettings.supplierId;
                              payload["customerId"] = pendingSuppliersList[index].customer_id;

                              bool requestStatus = await AppSettings.rejectRequest(payload);
                              if(requestStatus){
                                AppSettings.longSuccessToast("Rejected request Successfully");
                                await getPendingSuppliersData();

                              }
                              else{

                              }

                            },
                          ),
                        ],

                      ),
                    ),
                  );
                }) ),
          ]);
    }
    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 Data Found'),
                SizedBox(
                  height: 20,
                ),

              ],
            ),
          )
      );
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('Costumers'),
    backgroundColor: primaryColor,
    bottom: TabBar(
    controller: _controller,
    tabs: topTabs,
    indicatorColor: Colors.blue,
    unselectedLabelColor: Colors.white60,
    indicatorWeight: 2,
    ),),
     /* body: */
          body: TabBarView(controller: _controller, children: [
            /*Container(
          // color: Colors.lightGreenAccent,
          child: isTankerDataLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):_tanker(),
        ),*/
            Container(
              //color: Colors.lightBlueAccent,
              child: isPendingDataLoading?Center(
                child: CircularProgressIndicator(
                  color: primaryColor,
                  strokeWidth: 5.0,
                ),
              ):pendingCustomers(),
            ),
            Container(
              //color: Colors.lightBlueAccent,
              child: isConnectedDataLoading?Center(
                child: CircularProgressIndicator(
                  color: primaryColor,
                  strokeWidth: 5.0,
                ),
              ):connectedCustomers(),
            ),


          ]),
    );
  }

}
