import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/ordersProvider/pagesDashboardProvider.dart';
import 'package:generp/screens/screensExports.dart';
import 'package:provider/provider.dart';

import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../finance/FileViewer.dart';

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

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

  @override
  State<Ordersdetailsbymodes> createState() => _OrdersdetailsbymodesState();
}

class _OrdersdetailsbymodesState extends State<Ordersdetailsbymodes> {

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


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

        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(provider.subHeadings.length, (j) {
                        return Container(
                          padding: EdgeInsets.symmetric(vertical: 7),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Text(
                                  provider.Headings[j],
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 14,
                                    color: AppColors.semi_black,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: InkResponse(
                                  onTap: () {
                                    if (provider.Headings[j] ==
                                        "Purchase Order") {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder:
                                              (context) =>
                                              Fileviewer(
                                                fileName:
                                                orderDetails
                                                    .tpcPaymentAttachementViewFileName!,
                                                fileUrl:
                                                orderDetails
                                                    .tpcPaymentAttachmentDirFilePath!,
                                              ),
                                        ),
                                      );
                                    }
                                  },
                                  child: Text(
                                    provider.Headings[j] == "Purchase Order"
                                        ? "View"
                                        : "${provider.subHeadings[j]}",
                                    style: TextStyle(
                                      fontSize: 14,
                                      color:
                                      provider.Headings[j] == "Purchase Order"
                                          ? AppColors.app_blue
                                          : Color(0xFF818181),
                                      decoration:
                                      provider.Headings[j] == "Purchase Order"
                                          ? TextDecoration.underline
                                          : TextDecoration.none,
                                      decorationColor:
                                      provider.Headings[j] == "Purchase Order"
                                          ? AppColors.app_blue
                                          : AppColors.white,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        );
                      }),
                    ],
                  ),
                ),
              ),
            ),
            bottomNavigationBar:
            ["self","pending_approval"].contains(widget.mode) ?
            Container(height: 0) :
            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: [
                    if([
                      "level_one_approval",
                      "level_two_approval",
                      "level_two_rejected"
                    ].contains(widget.mode))...[
                      Expanded(
                        child: InkResponse(
                          onTap: () {
                            _showLevelApprovalRejectionSheet(context, "Reject");
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Color(0xFFFFEFEF),
                              border: Border.all(
                                color: Color(0xFFED3424),
                                width: 0.5,
                              ),
                            ),
                            child: Center(
                              child: Text(
                                "Reject",
                                style: TextStyle(
                                  color: Color(0xFFED3424),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                    SizedBox(width: 10),
                    if([
                      "level_one_approval",
                      "level_two_approval",
                      "level_two_rejected",
                      "sales_order_registered"
                    ].contains(widget.mode))...[
                      Expanded(
                        child: InkResponse(
                          onTap: () {
                            // provider
                            //     .approveRejectPaymentRequestAPIFunction(
                            //   context,
                            //   provider.requestsDetails.id,
                            // );
                            _showLevelApprovalRejectionSheet(
                                context, "Approve");
                          },
                          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),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],

                    if(["admin"].contains(widget.mode))...[
                      Expanded(
                        child: InkResponse(
                          onTap: () {
                            _showLevelDeletionSheet(context);
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Color(0xFFFFEFEF),
                              border: Border.all(
                                color: Color(0xFFED3424),
                                width: 0.5,
                              ),
                            ),
                            child: Center(
                              child: Text(
                                "Delete",
                                style: TextStyle(
                                  color: Color(0xFFED3424),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                    if(widget.mode == "dispatched")...[
                    ]

                  ],
                ),
              ),
            ),

          ),

          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: Consumer<Pagesdashboardprovider>(
                builder: (context, provider, child) {
                  return Container(
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),

                    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> _showLevelApprovalRejectionSheet(BuildContext context, type) {
    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<Pagesdashboardprovider>(

                builder: (context, provider, child) {
                  final details = provider.orderDetails;
                  return 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.topLeft,
                            child: Text(
                              type == "Approve" ? "${provider
                                  .approvalSheetHeading}" : "${provider
                                  .rejecetionSheetHeading}",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                              ),
                            ),
                          ),
                          if(widget.mode=="sales_order_registered")...[
                            Padding(
                              padding: const EdgeInsets.only(
                                  bottom: 5.0, top: 8.0),
                              child: Text("Company Name"),
                            ),
                            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: provider
                                      .editCompanyController,
                                  readOnly: true,
                                  keyboardType: TextInputType.text,
                                  maxLines: 1,
                                  onChanged: provider.onChangeEditCompanyName,
                                  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(provider.companyNameError!=null)...[
                            Container(
                              alignment: Alignment.topLeft,
                              margin: EdgeInsets.only(top: 2.5, left: 25),
                              child: Text(
                                "${provider.companyNameError}",
                                style: TextStyle(color: Colors.red, fontSize: 10),
                              ),
                            ),
                            ],
                            Padding(
                              padding: const EdgeInsets.only(
                                  bottom: 5.0, top: 8.0),
                              child: Text("Sale Order Number"),
                            ),
                            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: provider
                                      .saleOrderNumberController,
                                  readOnly: true,
                                  keyboardType: TextInputType.text,
                                  maxLines: 1,
                                  onChanged: provider.onChangeSaleOrderNumber,
                                  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(provider.saleOrderNumberError!=null)...[
                            Container(
                              alignment: Alignment.topLeft,
                              margin: EdgeInsets.only(top: 2.5, left: 25),
                              child: Text(
                                "${provider.saleOrderNumberError}",
                                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: provider
                                    .approveRejectFeedbackController,
                                readOnly: true,
                                keyboardType: TextInputType.text,
                                maxLines: 60,
                                onChanged: provider.onChangeApproveRejection,
                                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(provider.approveRejectFeedbackError!=null)...[
                          Container(
                            alignment: Alignment.topLeft,
                            margin: EdgeInsets.only(top: 2.5, left: 25),
                            child: Text(
                              "${provider.approveRejectFeedbackError}",
                              style: TextStyle(color: Colors.red, fontSize: 10),
                            ),
                          ),
                          ],
                          InkWell(
                            onTap: () {

                              provider.approvalRejectionAPIFunction(
                                  context,
                                  details.status,
                                  details.id,
                                  type=="Approve"?"Approved":"Rejected",
                                  details.tpcApplicable,
                                  details.tpcApplicable=="Yes"?(widget.mode=="level_one_approval"?details.level1TpcApprovedAmount:details.level2TpcApprovedAmount):"",
                                  widget.mode=="dispatched"?details.invoiceNumber:"",
                                  widget.mode=="dispatched"?details.vehicleNumber:"",
                                  widget.mode=="dispatched"?details.driverName:"",
                                  widget.mode=="dispatched"?details.driverMobileNumber:"",
                                  widget.mode=="dispatched"?[]:[],
                              widget.mode);
                            },

                            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> _showLevelDeletionSheet(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<Pagesdashboardprovider>(
                builder: (context, provider, child) {
                  return 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.topLeft,
                            child: Text(
                              "${provider.deletionSheetHeading}",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                              ),
                            ),
                          ),


                          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: provider.deleteFeedbackController,
                                readOnly: true,
                                keyboardType: TextInputType.text,
                                maxLines: 60,
                                onChanged:
                                provider.onChangeDeletion,
                                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(provider.deleteFeedbackError!=null)...[
                          Container(
                            alignment: Alignment.topLeft,
                            margin: EdgeInsets.only(top: 2.5, left: 25),
                            child: Text(
                              "${provider.deleteFeedbackError}",
                              style: TextStyle(color: Colors.red, fontSize: 10),
                            ),
                          ),
                          ],
                          InkWell(
                            onTap: () {
                              provider.delectionAPIFunction(
                                  context, provider.orderDetails.id);
                            },
                            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),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
