import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/users/pending_suppliers_model.dart';

import 'connected_users_model.dart';

class MyUsers extends StatefulWidget {

  var navigationFrom;

  MyUsers({this.navigationFrom});

  @override
  State<MyUsers> createState() => _MyUsersState();

}

class _MyUsersState extends State<MyUsers>
    with TickerProviderStateMixin {

  late TabController _controller;

  bool isPendingLoading=false;
  bool isConnectedLoading=false;
  bool isRejectedLoading=false;

  List<PendingSuppliersModel> pendingCustomersList=[];
  List<ConnectedCustomersModel> connectedCustomersList=[];
  List<PendingSuppliersModel> rejectedCustomersList=[];

  @override
  void initState(){

    super.initState();

    _controller=TabController(length:3,vsync:this);

    _controller.addListener(() {

      setState(() {});

    });

    getPendingCustomers();
    getConnectedCustomers();

  }

  Future<void> getPendingCustomers() async {

    setState(() {
      isPendingLoading=true;
    });

    try{

      var response=
      await AppSettings.getPendingSuppliers();

      setState(() {

        pendingCustomersList=
            ((jsonDecode(response)['data']) as List)
                .map((dynamic model){

              return PendingSuppliersModel.fromJson(model);

            }).toList();

        isPendingLoading=false;

      });

    }catch(e){

      setState(() {
        isPendingLoading=false;
      });

    }

  }

  Future<void> getConnectedCustomers() async {

    setState(() {

      isConnectedLoading=true;

    });

    try{

      var response=
      await AppSettings.getConnectedCustomers();

      setState(() {

        connectedCustomersList=
            ((jsonDecode(response)['data']) as List)
                .map((dynamic model){

              return ConnectedCustomersModel.fromJson(model);

            }).toList();

        isConnectedLoading=false;

      });

    }catch(e){

      setState(() {
        isConnectedLoading=false;
      });

    }

  }

  /*Future<void> getRejectedCustomers() async {

    setState(() {
      isRejectedLoading=true;
    });

    try{

      var response=
      await AppSettings.getRejectedCustomers();

      setState(() {

        rejectedCustomersList=
            ((jsonDecode(response)['data']) as List)
                .map((dynamic model){

              return PendingSuppliersModel.fromJson(model);

            }).toList();

        isRejectedLoading=false;

      });

    }catch(e){

      setState(() {
        isRejectedLoading=false;
      });

    }

  }*/

  Widget customerCard(String name,String phone,String address){

    return Container(

      decoration: BoxDecoration(

        color:Color(0XFFFFFFFF),

        borderRadius:BorderRadius.circular(12),

        border:Border.all(

          color:Colors.grey.shade300,

          width:1,

        ),

      ),

      child:Padding(

        padding:EdgeInsets.fromLTRB(10,10,10,10),

        child:Row(

          children:[

            CircleAvatar(

              radius:20,

              backgroundColor:Color(0XFFE8F2FF),

              child:Image.asset(

                'images/profile_user.png',

                width:50,

                height:50,

              ),

            ),

            SizedBox(width:10),

            Expanded(

              child:Column(

                crossAxisAlignment:
                CrossAxisAlignment.start,

                children:[

                  Text(

                    name,

                    style:fontTextStyle(

                        16,
                        Color(0XFF2D2E30),
                        FontWeight.w600),

                  ),

                  SizedBox(height:4),

                  Text(

                    phone,

                    style:fontTextStyle(

                        12,
                        Color(0XFF515253),
                        FontWeight.w400),

                  ),

                  SizedBox(height:4),

                  Text(

                    address,

                    style:fontTextStyle(

                        12,
                        Color(0XFF515253),
                        FontWeight.w400),

                  ),

                ],

              ),

            )

          ],

        ),

      ),

    );

  }

  Widget pendingTab(){

    if(isPendingLoading){

      return Center(

        child:CircularProgressIndicator(

          color:primaryColor,

        ),

      );

    }

    if(pendingCustomersList.isEmpty){

      return Center(
        child:Text("No Pending Customers"),
      );

    }

    return ListView.separated(

        padding:EdgeInsets.all(10),

        itemCount:pendingCustomersList.length,

        separatorBuilder:(c,i)=>SizedBox(height:10),

        itemBuilder:(context,index){

          return Column(

            children:[

              customerCard(

                  pendingCustomersList[index].customer_name,

                  pendingCustomersList[index].customer_phone_number,

                  pendingCustomersList[index].customer_address

              ),

              SizedBox(height:8),

              Row(

                children:[

                  Expanded(

                    child:GestureDetector(

                      onTap:() async {

                        var payload={};

                        payload["supplierId"]=
                            AppSettings.supplierId;

                        payload["customerId"]=
                            pendingCustomersList[index]
                                .customer_id;

                        bool status=
                        await AppSettings.acceptRequest(
                            payload);

                        if(status){

                          AppSettings.longSuccessToast(
                              "Accepted");

                          getPendingCustomers();
                          getConnectedCustomers();

                        }

                      },

                      child:Container(

                        decoration:BoxDecoration(

                          color:Colors.white,

                          border:Border.all(
                              color:Color(0XFF098603)
                          ),

                          borderRadius:
                          BorderRadius.circular(24),

                        ),

                        padding:EdgeInsets.symmetric(
                            vertical:12),

                        alignment:Alignment.center,

                        child:Text(

                          "Accept",

                          style:fontTextStyle(

                              12,
                              Color(0XFF098603),
                              FontWeight.w600),

                        ),

                      ),

                    ),

                  ),

                  SizedBox(width:10),

                  Expanded(

                    child:GestureDetector(

                      onTap:() async {

                        var payload={};

                        payload["supplierId"]=
                            AppSettings.supplierId;

                        payload["customerId"]=
                            pendingCustomersList[index]
                                .customer_id;

                        bool status=
                        await AppSettings.rejectRequest(
                            payload);

                        if(status){

                          AppSettings.longSuccessToast(
                              "Rejected");

                          getPendingCustomers();
                          //getRejectedCustomers();

                        }

                      },

                      child:Container(

                        decoration:BoxDecoration(

                          color:Colors.white,

                          border:Border.all(
                              color:Colors.red
                          ),

                          borderRadius:
                          BorderRadius.circular(24),

                        ),

                        padding:EdgeInsets.symmetric(
                            vertical:12),

                        alignment:Alignment.center,

                        child:Text(

                          "Reject",

                          style:fontTextStyle(

                              12,
                              Colors.red,
                              FontWeight.w600),

                        ),

                      ),

                    ),

                  )

                ],

              )

            ],

          );

        }

    );

  }

  Widget connectedTab(){

    if(isConnectedLoading){

      return Center(

        child:CircularProgressIndicator(
            color:primaryColor),

      );

    }

    if(connectedCustomersList.isEmpty){

      return Center(
        child:Text("No Connected Customers"),
      );

    }

    return ListView.separated(

        padding:EdgeInsets.all(10),

        itemCount:connectedCustomersList.length,

        separatorBuilder:(c,i)=>SizedBox(height:10),

        itemBuilder:(context,index){

          return customerCard(

              connectedCustomersList[index].customer_name,

              connectedCustomersList[index]
                  .customer_phone_number,

              connectedCustomersList[index]
                  .customer_address

          );

        }

    );

  }

  Widget rejectedTab(){

    if(isRejectedLoading){

      return Center(

        child:CircularProgressIndicator(
            color:primaryColor),

      );

    }

    if(rejectedCustomersList.isEmpty){

      return Center(
        child:Text("No Rejected Requests"),
      );

    }

    return ListView.separated(

        padding:EdgeInsets.all(10),

        itemCount:rejectedCustomersList.length,

        separatorBuilder:(c,i)=>SizedBox(height:10),

        itemBuilder:(context,index){

          return customerCard(

              rejectedCustomersList[index].customer_name,

              rejectedCustomersList[index]
                  .customer_phone_number,

              rejectedCustomersList[index]
                  .customer_address

          );

        }

    );

  }

  @override
  Widget build(BuildContext context){

    return Scaffold(

      backgroundColor:Colors.white,

      appBar:AppBar(

        elevation:0,

        backgroundColor:Colors.white,

        title:Text(

          "Customers",

          style:fontTextStyle(
              14,
              Color(0XFF2A2A2A),
              FontWeight.w500),

        ),

        bottom:PreferredSize(

          preferredSize:Size.fromHeight(70),

          child:Container(

            margin:EdgeInsets.symmetric(
                horizontal:16,
                vertical:8),

            padding:EdgeInsets.all(4),

            decoration:BoxDecoration(

              color:Color(0xFFF5F6F6),

              borderRadius:
              BorderRadius.circular(23),

            ),

            child:ClipRRect(

              borderRadius:
              BorderRadius.circular(19),

              child:TabBar(

                controller:_controller,

                indicator:BoxDecoration(),

                dividerColor:Colors.transparent,

                tabs:List.generate(3,(index){

                  final labels=[
                    "Pending",
                    "Connected",
                    "Rejected"
                  ];

                  return Container(

                    decoration:BoxDecoration(

                      color:_controller.index==index
                          ?Color(0XFFF5CD47)
                          :Color(0xFFF5F6F6),

                      borderRadius:
                      BorderRadius.circular(27),

                    ),

                    child:Tab(

                      child:Center(

                        child:Text(

                          labels[index],

                          style:fontTextStyle(

                              12,
                              Color(0XFF3B3B3B),
                              FontWeight.w600),

                        ),

                      ),

                    ),

                  );

                }),

              ),

            ),

          ),

        ),

      ),

      body:TabBarView(

        controller:_controller,

        children:[

          pendingTab(),

          connectedTab(),

          rejectedTab(),

        ],

      ),

    );

  }

}