import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/screens/order/tpcAgentIssueListDetails.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../Notifiers/ordersProvider/tpcAgentsProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';
import 'ordersDetailsByModes.dart';

class Tpcagentissuelist extends StatefulWidget {
  final pageTitleName;
  final mode;
  const Tpcagentissuelist({
    super.key,
    required this.pageTitleName,
    required this.mode,
  });

  @override
  State<Tpcagentissuelist> createState() => _TpcagentissuelistState();
}

class _TpcagentissuelistState extends State<Tpcagentissuelist> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = Provider.of<Tpcagentsprovider>(context, listen: false);
      provider.resetPagination(); //  clear before first load
      provider.TPCAgentsIssueListAPIFunction(context);
    });

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200) {
        final provider = Provider.of<Tpcagentsprovider>(context, listen: false);
        provider.loadMoreIssues(context);
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _connectivity.disposeStream();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return (connection == "Online")
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () {
                Provider.of<Tpcagentsprovider>(
                  context,
                  listen: false,
                ).resetAll();
                return onBackPressed(context);
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Tpcagentsprovider>(
      builder: (context, provider, child) {
        final tpcAgentsIssueList = provider.tpcAgentsIssueList;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2New(
            context,
            widget.pageTitleName,
            provider.resetAll,
            Row(
              children: [
                // InkResponse(
                //   onTap: () {
                //     // _showOptionsSheet(context);
                //   },
                //   child: SvgPicture.asset("assets/svg/ic_download.svg",),
                // ),
              ],
            ),
            0xFFFFFFFF,
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body:
              provider.isLoading && tpcAgentsIssueList.isEmpty
                  ? Center(
                    child: CircularProgressIndicator.adaptive(
                      valueColor: AlwaysStoppedAnimation<Color>(
                        AppColors.app_blue,
                      ),
                    ),
                  )
                  : tpcAgentsIssueList.isNotEmpty
                  ? RefreshIndicator(
                    onRefresh: () async {
                      provider.resetPagination();
                      await provider.TPCAgentsIssueListAPIFunction(context);
                    },
                    child: ListView.builder(
                      controller: _scrollController,
                      itemCount:
                          tpcAgentsIssueList.length +
                          (provider.hasMoreData ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index == tpcAgentsIssueList.length) {
                          return provider.isLoadingMore
                              ? const Padding(
                                padding: EdgeInsets.all(16),
                                child: Center(
                                  child: CircularProgressIndicator(),
                                ),
                              )
                              : const SizedBox.shrink();
                        }

                        final issue = tpcAgentsIssueList[index];
                        return InkResponse(
                          onTap: () async {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => Tpcagentissuelistdetails(
                                      pageTitleName: "CRM Order Details",
                                      mode: widget.mode,
                                      orderId:
                                          tpcAgentsIssueList[index].orderId,
                                    ),
                              ),
                            );
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 7.5,
                              vertical: 5,
                            ),
                            margin: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 5,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Column(
                              children: [
                                Row(
                                  children: [
                                    Expanded(
                                      flex: 1,
                                      child: SizedBox(
                                        height: 50,
                                        width: 35,

                                        child: SvgPicture.asset(
                                          "assets/svg/order/tpc_list_ic.svg",
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    Expanded(
                                      flex: 4,
                                      child: SizedBox(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              tpcAgentsIssueList[index].name!,
                                              style: TextStyle(
                                                fontFamily: "JakartaRegular",
                                                fontSize: 14,
                                                color: AppColors.semi_black,
                                              ),
                                            ),
                                            Text(
                                              "${tpcAgentsIssueList[index].aname}",
                                              style: TextStyle(
                                                fontFamily: "JakartaRegular",
                                                fontSize: 14,
                                                color: AppColors.grey_semi,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    Expanded(
                                      flex: 1,
                                      child: InkResponse(
                                        onTap: () {
                                          launch(
                                            'tel://${tpcAgentsIssueList[index].mobileNumber}',
                                          );
                                        },
                                        child: SizedBox(
                                          height: 35,
                                          width: 35,
                                          child: SvgPicture.asset(
                                            "assets/svg/crm/lead_list_call_ic.svg",
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  )
                  : Emptywidget(context),
        );
      },
    );
  }

  Widget _scaffold1(BuildContext context) {
    return Consumer<Tpcagentsprovider>(
      builder: (context, provider, child) {
        final tpcAgentsIssueList = provider.tpcAgentsIssueList;
        return WillPopScope(
          onWillPop: () {
            provider.resetAll();
            return onBackPressed(context);
          },
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              appBar: appbar2(
                context,
                widget.pageTitleName,
                provider.resetAll,
                Row(
                  children: [
                    // InkResponse(
                    //   onTap: () {
                    //     // _showOptionsSheet(context);
                    //   },
                    //   child: SvgPicture.asset("assets/svg/ic_download.svg",),
                    // ),
                  ],
                ),
              ),
              backgroundColor: AppColors.scaffold_bg_color,
              body:
                  provider.isLoading
                      ? Center(
                        child: CircularProgressIndicator.adaptive(
                          valueColor: AlwaysStoppedAnimation<Color>(
                            AppColors.app_blue,
                          ),
                        ),
                      )
                      : tpcAgentsIssueList.isNotEmpty
                      ? SingleChildScrollView(
                        child: Column(
                          children: [
                            ListView.builder(
                              itemCount: tpcAgentsIssueList.length,
                              shrinkWrap: true,
                              physics: NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                if (tpcAgentsIssueList.isEmpty) {
                                  return SizedBox(
                                    child: Center(
                                      child: Text("No Data Available"),
                                    ),
                                  );
                                }
                                return Container(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 10,
                                    vertical: 10,
                                  ),
                                  margin: EdgeInsets.symmetric(
                                    horizontal: 10,
                                    vertical: 10,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(16),
                                  ),
                                  child: Column(
                                    children: [
                                      Row(
                                        children: [
                                          Expanded(
                                            flex: 1,
                                            child: Container(
                                              height: 50,
                                              width: 35,

                                              decoration: BoxDecoration(
                                                color: Color(0xFFEAF7FF),
                                                borderRadius:
                                                    BorderRadius.circular(8),
                                              ),
                                              child: SvgPicture.asset(
                                                "assets/svg/tpc_ic.svg",
                                              ),
                                            ),
                                          ),
                                          SizedBox(width: 10),
                                          Expanded(
                                            flex: 4,
                                            child: SizedBox(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    tpcAgentsIssueList[index]
                                                        .name!,
                                                    style: TextStyle(
                                                      fontFamily:
                                                          "JakartaMedium",
                                                      fontSize: 14,
                                                      color:
                                                          AppColors.semi_black,
                                                    ),
                                                  ),
                                                  Text(
                                                    "${tpcAgentsIssueList[index].aname}",
                                                    style: TextStyle(
                                                      fontFamily:
                                                          "JakartaMedium",
                                                      fontSize: 14,
                                                      color: AppColors.app_blue,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      Divider(
                                        thickness: 0.5,
                                        color: Color(0xFFD7D7D7),
                                      ),
                                      ...List.generate(4, (j) {
                                        final headings = [
                                          "Sales Person",
                                          "Order Number",
                                          "Order Amount",
                                          "Order Status",
                                        ];

                                        final subHeadings = [
                                          tpcAgentsIssueList[index].ename,
                                          tpcAgentsIssueList[index].orderNumber,
                                          tpcAgentsIssueList[index].totalAmount,
                                          tpcAgentsIssueList[index].status,
                                        ];
                                        return Container(
                                          padding: EdgeInsets.symmetric(
                                            vertical: 5,
                                          ),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Expanded(
                                                child: Text(
                                                  headings[j],
                                                  style: TextStyle(
                                                    fontFamily: "JakartaMedium",
                                                    fontSize: 14,
                                                    color: AppColors.semi_black,
                                                  ),
                                                ),
                                              ),
                                              Expanded(
                                                child: InkResponse(
                                                  child: Text(
                                                    "${subHeadings[j]}",
                                                    style: TextStyle(
                                                      fontSize: 14,
                                                      color: Color(0xFF818181),
                                                      decoration:
                                                          TextDecoration.none,
                                                      decorationColor:
                                                          AppColors.white,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        );
                                      }),
                                      InkResponse(
                                        onTap: () async {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder:
                                                  (
                                                    context,
                                                  ) => Tpcagentissuelistdetails(
                                                    pageTitleName:
                                                        "CRM Order Details",
                                                    mode: widget.mode,
                                                    orderId:
                                                        tpcAgentsIssueList[index]
                                                            .orderId,
                                                  ),
                                            ),
                                          );
                                        },
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            vertical: 5,
                                          ),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            children: [
                                              Text(
                                                "View Details",
                                                style: TextStyle(
                                                  fontFamily: "JakartaMedium",
                                                  fontSize: 14,
                                                  color: AppColors.app_blue,
                                                ),
                                              ),
                                              SizedBox(width: 5),
                                              SvgPicture.asset(
                                                "assets/svg/next_button.svg",
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      )
                      : Emptywidget(context),
            ),
          ),
        );
      },
    );
  }
}
