import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/screens/screensExports.dart';
import 'package:generp/screens/notifierExports.dart';
import 'package:provider/provider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../finance/FileViewer.dart';

class Tpcagentissuelistdetails extends StatefulWidget {
  final pageTitleName;
  final orderId;
  final mode;

  const Tpcagentissuelistdetails(
      {super.key, required this.pageTitleName, required this.orderId, required this.mode});

  @override
  State<Tpcagentissuelistdetails> createState() => _TpcagentissuelistdetailsState();
}

class _TpcagentissuelistdetailsState extends State<Tpcagentissuelistdetails> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Pagesdashboardprovider>(
        context,
        listen: false,
      );
      provider.showMoreDetails = false;

      provider.ordersDetailsByModeAPIFunction(
          context, widget.orderId, widget.mode);
    });
  }


  @override
  Widget build(BuildContext context) {
    return Consumer2<Pagesdashboardprovider,Tpcagentsprovider>(
      builder: (context, provider,tpcProvider, child) {
        var orderDetails = provider.orderDetails;

        var Headings1 = [
          "Order Number",
          "Account Name",
          "Sales Person Name",
          "Order Received Date",
        ];
        var subHeadings1 = [
          provider.orderDetails.orderNumber ?? "-",
          provider.orderDetails.accountName ?? "-",
          provider.orderDetails.salesPersonEmpName ?? "-",
          provider.orderDetails.orderReceivedDate ?? "-",
        ];


        var Headings2 = [
          "Billing State",
          "Billing District",
          "Billing Sub Location",
          "Billing Pincode",
          "Billing Address",

          "Entered By",

          "Dispatch State",
          "Dispatch District",
          "District Sub Location",
          "Dispatch Pincode",
          "Dispatch Address",

          "GST Number",

          "Unloading Scope",
          "Freight Scope",
          "Erection Scope",

          "CGST Amount",
          "SGST Amount",
          "IGST Amount",

          "OTP",

          "Basic Amount",
          "Paid Amount",
          "Balance Amount",
          "Total Amount",

          "TPC Applicable",
          "TPC Agent",
          "TPC Requested Amount",

          "TPC Level 1 Approved Amount",
          "TPC Level 2 Approved Amount",

          "TPC Payment Mode",
          "TPC Payment Reference No",
          "TPC Payment Attachment",
          "TPC Status",
          "Purchase Order",

          "Created Datetime",
          "Note",
          "Status",
        ];
        var subHeadings2 = [

          provider.orderDetails.billingState ?? "-",
          provider.orderDetails.billingDistrict ?? "-",
          provider.orderDetails.billingSubLocality ?? "-",
          provider.orderDetails.billingPincode ?? "-",
          provider.orderDetails.billingAddress ?? "-",

          provider.orderDetails.enteredEmpName ?? "-",

          provider.orderDetails.stateName ?? "-",
          provider.orderDetails.districtName ?? "-",
          provider.orderDetails.subLocationName ?? "-",
          provider.orderDetails.dispatchPincode ?? "-",
          provider.orderDetails.dispatchAddress ?? "-",

          provider.orderDetails.gstNumber ?? "-",

          provider.orderDetails.unloadingScope ?? "-",
          provider.orderDetails.freightScope ?? "-",
          provider.orderDetails.erectionScope ?? "-",

          provider.orderDetails.cgstAmount ?? "-",
          provider.orderDetails.sgstAmount ?? "-",
          provider.orderDetails.igstAmount ?? "-",

          provider.orderDetails.otp ?? "-",

          provider.orderDetails.basicAmount ?? "-",
          provider.orderDetails.paidAmount ?? "-",
          provider.orderDetails.balanceAmount ?? "-",
          provider.orderDetails.totalAmount ?? "-",

          provider.orderDetails.tpcApplicable ?? "-",
          provider.orderDetails.tpcaAgentName ?? "-",
          provider.orderDetails.requestedTpcAmount ?? "-",

          provider.orderDetails.level1TpcApprovedAmount ?? "-",
          provider.orderDetails.level2TpcApprovedAmount ?? "-",

          provider.orderDetails.tpcPaymentMode ?? "-",
          provider.orderDetails.tpcPaymentReferenceNo ?? "-",
          provider.orderDetails.tpcPaymentAttachementViewFileName ?? "-",
          provider.orderDetails.tpcStatus ?? "-",
          provider.orderDetails.tpcPaymentAttachmentDirFilePath ?? "-",

          provider.orderDetails.createdDatetime ?? "-",
          provider.orderDetails.note ?? "-",
          provider.orderDetails.status ?? "-",
        ];






        var Headings = [...Headings1];
        var subHeadings = [...subHeadings1];


        if(provider.showMoreDetails){
          Headings = [...Headings1,...Headings2];
          subHeadings = [...subHeadings1,...subHeadings2];
        }
        return WillPopScope(
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: appbar2(context, widget.pageTitleName, provider.resetAll,
              InkResponse(
                onTap: () {
                  _showOptionsSheet(
                      context
                  );
                },
                child: SvgPicture.asset("assets/svg/ic_more.svg", height: 30,),
              ),),
            backgroundColor: AppColors.scaffold_bg_color,
            body: Container(
              child: SingleChildScrollView(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Expanded(
                            flex: 1,
                            child: Container(
                              height: 50,
                              width: 35,
                              padding: EdgeInsets.all(8.0),
                              decoration: BoxDecoration(
                                color: Color(0xFFFFF3CE),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: SvgPicture.asset("assets/svg/fin_ic.svg"),
                            ),
                          ),
                          SizedBox(width: 10),
                          Expanded(
                            flex: 4,
                            child: SizedBox(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    orderDetails.accountName ?? "-",
                                    style: TextStyle(
                                      fontFamily: "JakartaMedium",
                                      fontSize: 14,
                                      color: AppColors.semi_black,
                                    ),
                                  ),
                                  Text(
                                    "₹${orderDetails.balanceAmount}",
                                    style: TextStyle(
                                      fontFamily: "JakartaMedium",
                                      fontSize: 14,
                                      color: AppColors.app_blue,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 2,
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 5,
                                vertical: 10,
                              ),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                color: Color(0xFFE3FFE0),
                              ),
                              child: Center(
                                child: Text(
                                  orderDetails.status ?? "-",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 14,
                                    color: Color(0xFF0D9C00),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(thickness: 0.5, color: Color(0xFFD7D7D7)),
                      ...List.generate(subHeadings.length, (j) {
                        return Container(
                          padding: EdgeInsets.symmetric(vertical: 7),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Text(
                                  Headings[j],
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 14,
                                    color: AppColors.semi_black,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: InkResponse(
                                  onTap: () {
                                    if (Headings[j] ==
                                        "Purchase Order") {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder:
                                              (context) =>
                                              Fileviewer(
                                                fileName:
                                                orderDetails
                                                    .tpcPaymentAttachementViewFileName!,
                                                fileUrl:
                                                orderDetails
                                                    .tpcPaymentAttachmentDirFilePath!,
                                              ),
                                        ),
                                      );
                                    }
                                  },
                                  child: Text(
                                    Headings[j] == "Purchase Order"
                                        ? "View"
                                        : "${subHeadings[j]}",
                                    style: TextStyle(
                                      fontSize: 14,
                                      color:
                                      Headings[j] == "Purchase Order"
                                          ? AppColors.app_blue
                                          : Color(0xFF818181),
                                      decoration:
                                      Headings[j] == "Purchase Order"
                                          ? TextDecoration.underline
                                          : TextDecoration.none,
                                      decorationColor:
                                      Headings[j] == "Purchase Order"
                                          ? AppColors.app_blue
                                          : AppColors.white,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        );
                      }),
                      InkResponse(
                        onTap: () async {
                          provider.showMoreDetails = !provider.showMoreDetails;
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            vertical: 5,
                          ),
                          child: Row(
                            crossAxisAlignment:
                            CrossAxisAlignment.center,
                            mainAxisAlignment:
                            MainAxisAlignment.center,
                            children: [
                              Text(
                                provider.showMoreDetails?"- Show Less": "+ More Details",
                                style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  fontSize: 14,
                                  color: AppColors.app_blue,
                                ),
                              ),

                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            bottomNavigationBar:

            Container(
              margin: EdgeInsets.symmetric(horizontal: 10),
              alignment: Alignment.bottomCenter,
              height: 60,
              child: Container(
                margin: EdgeInsets.only(bottom: 10),
                alignment: Alignment.center,
                height: 45,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [

                      Expanded(
                        child: InkResponse(
                          onTap: () {
                            // provider
                            //     .approveRejectPaymentRequestAPIFunction(
                            //   context,
                            //   provider.requestsDetails.id,
                            // );
                            _showLevelApprovalSheet(
                                context);
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Color(0xFFE7FFE5),
                              border: Border.all(
                                color: Color(0xFF0D9C00),
                                width: 0.5,
                              ),
                            ),
                            child: Center(
                              child: Text(
                                "Approve",
                                style: TextStyle(
                                  color: Color(0xFF0D9C00),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),




                  ],
                ),
              ),
            ),

          ),

          onWillPop: () {
            return onBackPressed(context);
          },
        );
      },
    );
  }


  Future<void> _showOptionsSheet(BuildContext context,) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer2<Pagesdashboardprovider,Tpcagentsprovider>(
                builder: (context, provider,tpcProvider, child) {
                  return Container(
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),
                    padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom,),
                    child: SingleChildScrollView(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(height: 15),

                          ...List.generate(3, (index) {
                            final assetnames = [
                              "order_list_svg_1",
                              "order_list_svg_2",
                              "order_list_svg_3",
                            ];
                            final Headingnames = [
                              "Payment History",
                              "Products Details",
                              "Feedback History",
                            ];
                            return ListTile(
                              onTap: () async {
                                switch (index) {
                                  case 0:
                                    Navigator.pop(context);
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) =>
                                            Orderdetailspaymenthistory(
                                            ),
                                      ),
                                    );
                                    break;
                                  case 1:
                                    Navigator.pop(context);
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) =>
                                            Orderdetailsproductshistory(
                                            ),
                                      ),
                                    );
                                    break;
                                  case 2:
                                    Navigator.pop(context);
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) =>
                                            Orderdetailsfeedbackhistory(

                                            ),
                                      ),
                                    );
                                    break;
                                }
                              },
                              leading: SvgPicture.asset(
                                "assets/svg/${assetnames[index]}.svg",
                              ),
                              title: Text(Headingnames[index], style: TextStyle(
                                  fontFamily: "JakartaMedium"
                              ),),
                              trailing: SvgPicture.asset(
                                "assets/svg/arrow_right_new.svg",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }




  Future<void> _showLevelApprovalSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Tpcagentsprovider>(

                builder: (context,tcpProvider, child) {
                  return Container(
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),
                    padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom,),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Align(
                            alignment: Alignment.topLeft,
                            child: Text(
                              "Update Issue",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                              ),
                            ),
                          ),

                            Padding(
                              padding: const EdgeInsets.only(
                                  bottom: 5.0, top: 8.0),
                              child: Text("TPC Payment Mode"),
                            ),
                            Container(
                              height: 50,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: Color(0xFFE9E9E9),
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(
                                    10.0, 0.0, 10, 0),
                                child: TextFormField(
                                  controller: tcpProvider
                                      .tpcPaymentModeController,
                                  readOnly: true,
                                  keyboardType: TextInputType.text,
                                  maxLines: 1,
                                  onChanged: tcpProvider.onChangeTPCPayment,
                                  style: TextStyle(
                                      color: Color(0xFF818181), fontSize: 14),
                                  decoration: InputDecoration(
                                    hintText: "Enter Company Name",
                                    hintStyle: TextStyle(
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xFFB4BEC0),
                                      fontSize: 14,
                                    ),

                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                  ),
                                ),
                              ),
                            ),
                            if(tcpProvider.tpcPaymentModeError!=null)...[
                              Container(
                                alignment: Alignment.topLeft,
                                margin: EdgeInsets.only(top: 2.5, left: 25),
                                child: Text(
                                  "${tcpProvider.tpcPaymentModeError}",
                                  style: TextStyle(color: Colors.red, fontSize: 10),
                                ),
                              ),
                            ],
                            Padding(
                              padding: const EdgeInsets.only(
                                  bottom: 5.0, top: 8.0),
                              child: Text("TPC Payment Reference No. /Cheque No. / UTR No."),
                            ),
                            Container(
                              height: 50,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: Color(0xFFE9E9E9),
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(
                                    10.0, 0.0, 10, 0),
                                child: TextFormField(
                                  controller: tcpProvider
                                      .tpcPaymentModeController,
                                  readOnly: true,
                                  keyboardType: TextInputType.text,
                                  maxLines: 1,
                                  onChanged: tcpProvider.onChangeTPCPaymentReference,
                                  style: TextStyle(
                                      color: Color(0xFF818181), fontSize: 14),
                                  decoration: InputDecoration(
                                    hintText: "Enter Order Number",
                                    hintStyle: TextStyle(
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xFFB4BEC0),
                                      fontSize: 14,
                                    ),

                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                  ),
                                ),
                              ),
                            ),
                            if(tcpProvider.tpcPaymentReferenceNoError!=null)...[
                              Container(
                                alignment: Alignment.topLeft,
                                margin: EdgeInsets.only(top: 2.5, left: 25),
                                child: Text(
                                  "${tcpProvider.tpcPaymentReferenceNoError}",
                                  style: TextStyle(color: Colors.red, fontSize: 10),
                                ),
                              ),
                            ],



                          Padding(
                            padding: const EdgeInsets.only(
                                bottom: 5.0, top: 8.0),
                            child: Text("Remarks"),
                          ),
                          Container(
                            height: 150,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: Color(0xFFE9E9E9),
                              borderRadius: BorderRadius.circular(14),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.fromLTRB(
                                  10.0, 0.0, 10, 0),
                              child: TextFormField(
                                controller: tcpProvider
                                    .orderTpcFeedbackController,
                                readOnly: true,
                                keyboardType: TextInputType.text,
                                maxLines: 60,
                                onChanged: tcpProvider.onChangeTpcFeedback,
                                style: TextStyle(
                                    color: Color(0xFF818181), fontSize: 14),
                                decoration: InputDecoration(
                                  hintText: "Write Remarks",
                                  hintStyle: TextStyle(
                                    fontWeight: FontWeight.w400,
                                    color: Color(0xFFB4BEC0),
                                    fontSize: 14,
                                  ),

                                  enabledBorder: InputBorder.none,
                                  focusedBorder: InputBorder.none,
                                ),
                              ),
                            ),
                          ),
                          if(tcpProvider.orderTpcFeedbackError!=null)...[
                            Container(
                              alignment: Alignment.topLeft,
                              margin: EdgeInsets.only(top: 2.5, left: 25),
                              child: Text(
                                "${tcpProvider.orderTpcFeedbackError}",
                                style: TextStyle(color: Colors.red, fontSize: 10),
                              ),
                            ),
                          ],
                          InkResponse(
                            onTap: () {
                              _showAttachmentSheet(context);
                            },
                            child: Container(
                              margin: EdgeInsets.symmetric(vertical: 10),
                              height: 45,
                              width: MediaQuery.of(context).size.width,
                              decoration: BoxDecoration(
                                color: Color(0xFFE6F6FF),
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: AppColors.app_blue,
                                  width: 0.5,
                                ),
                              ),
                              child: Center(
                                child: Text(
                                  "Add Attachment",
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    color: AppColors.app_blue,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          if(tcpProvider.imagePicked==1 && tcpProvider.imagePath!=null)...[
                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 4.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text("${tcpProvider.imagePath}",style: TextStyle(
                                      color: AppColors.semi_black,
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600
                                  ),),
                                  InkResponse(
                                      onTap: () {
                                        tcpProvider.imagePicked = 0;
                                        tcpProvider.imagePath = null;
                                        tcpProvider.imageFilePath = null;
                                      },
                                      child: SvgPicture.asset("assets/svg/ic_close.svg",width: 15,height: 15,))
                                ],
                              ),
                            )
                          ],

                          InkWell(
                            onTap: () {
                              tcpProvider.TPCAgentsIssueApprovalAPIFunction(context, widget.orderId);
                            },

                            child: Container(
                              alignment: Alignment.center,
                              height: 45,
                              margin: EdgeInsets.only(
                                left: 5.0,
                                right: 5.0,
                                top: 5.0,
                                bottom: 5.0,
                              ),
                              decoration: BoxDecoration(
                                color: AppColors.app_blue, //1487C9
                                borderRadius: BorderRadius.circular(14.0),
                              ),
                              child: Center(
                                child: Text(
                                  "Submit",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }

  Future<void> _showAttachmentSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
               child: Consumer<Tpcagentsprovider>(

            builder: (context,tcpProvider, child) {
                  return Padding(

                    padding: EdgeInsets.only(
                      bottom:
                      MediaQuery
                          .of(
                        context,
                      )
                          .viewInsets
                          .bottom, // This handles keyboard
                    ),
                    child: Container(
                      margin: EdgeInsets.only(
                        bottom: 15,
                        left: 15,
                        right: 15,
                        top: 10,
                      ),

                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                "Select Source",
                                style: TextStyle(
                                    color: AppColors.app_blue,
                                    fontSize: 16
                                ),
                              ),
                            ),
                            SizedBox(height: 15,),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                tcpProvider.imgFromGallery(context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                tcpProvider.imgFromCamera(
                                    context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }

}
