import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/financeProvider/paymentRequisitionPaymentsListProvider.dart';
import '../../Utils/commonServices.dart';
import '../commom/accountsListDetails.dart';
import 'FileViewer.dart';

class Paymentdetailspaymentrequisition extends StatefulWidget {
  final paymentRequestId;
  final pageName;

  const Paymentdetailspaymentrequisition({
    super.key,
    required this.paymentRequestId,
    required this.pageName,
  });

  @override
  State<Paymentdetailspaymentrequisition> createState() =>
      _PaymentdetailspaymentrequisitionState();
}

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

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Paymentrequisitionpaymentslistprovider>(
        context,
        listen: false,
      );
      provider.paymentsListDetailsAPI(context, widget.paymentRequestId);
      provider.showMoreDetails = false;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _connectivity.disposeStream();
  }

  @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: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Paymentrequisitionpaymentslistprovider>(
      builder: (context, provider, child) {
        var payment_det = provider.paymentDetails;
        final headings1 = ["From Account", "Created Employee"];
        final subHeadings1 = [
          payment_det.paymentAccountName ?? "-",
          payment_det.paymentEmployeeName ?? "-",
        ];
        final headings2 = [
          "Bank Name",
          "Account Holder Name",
          "Account Number",
          "Branch",
          "IFSC",
          "UPI ID",
        ];
        final subHeadings2 = [
          payment_det.bankName ?? "-",
          payment_det.bankAccountHolderName ?? "-",
          payment_det.bankAccountNumber ?? "-",
          payment_det.bankBranchName ?? "-",
          payment_det.bankIfscCode ?? "-",
          payment_det.bankUpiId ?? "-",
        ];
        final headings3 = [
          "Payment Mode",
          "Payment Reference",
          "Attachment",
          "Payment Date",
        ];
        final subHeadings3 = [
          payment_det.mode ?? "-",
          payment_det.paymentReferenceNumber ?? "-",
          "View",
          payment_det.paymentDate ?? "-",
        ];

        final sections = [
          {
            "title": "Account Details",
            "headings": headings1,
            "subHeadings": subHeadings1,
          },
          if (provider.showMoreDetails) ...[
            {
              "title": "Bank Details",
              "headings": headings2,
              "subHeadings": subHeadings2,
            },
            {
              "title": "Payment Details",
              "headings": headings3,
              "subHeadings": subHeadings3,
            },
          ],
        ];
        var clickable = sections.any(
          (element) => [
            "From Account",
            "Created Employee",
            "Attachment",
          ].contains(element["headings"]),
        );
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar(context, widget.pageName),
          backgroundColor: AppColors.scaffold_bg_color,
          body: SizedBox(
            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: 45,
                            width: 45,
                            padding: EdgeInsets.all(7.5),
                            decoration: BoxDecoration(
                              color: Color(0xFFE6F6FF),
                              shape: BoxShape.circle,
                              // 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: [
                                InkResponse(
                                  onTap: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Accountslistdetails(
                                              accountID: payment_det.accountId,
                                            ),
                                      ),
                                    );
                                  },
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 6,
                                    ),
                                    child: Text(
                                      payment_det.accountName ?? "-",
                                      style: TextStyle(
                                        decoration: TextDecoration.underline,
                                        decorationColor: AppColors.grey_thick,
                                        decorationStyle:
                                            TextDecorationStyle.dotted,
                                        height: 1.5,
                                        fontFamily: "JakartaRegular",
                                        fontSize: 14,
                                        color: AppColors.semi_black,
                                      ),
                                    ),
                                  ),
                                ),
                                Text(
                                  "₹${payment_det.amount}",
                                  style: TextStyle(
                                    fontFamily: "JakartaRegular",
                                    fontSize: 14,
                                    color: AppColors.grey_semi,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        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(
                                payment_det.refType ?? "-",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  fontSize: 14,
                                  color: Color(0xFF0D9C00),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    Column(
                      children: List.generate(sections.length, (sectionIndex) {
                        final section = sections[sectionIndex];
                        final title = section["title"] as String;
                        final headings = section["headings"] as List<String>;
                        final subHeadings =
                            section["subHeadings"] as List<String>;

                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(vertical: 4),
                              child: Row(
                                children: [
                                  Expanded(
                                    flex: 3,
                                    child: Text(
                                      title,
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontFamily: "JakartaSemiBold",
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 6,
                                    child: DottedLine(
                                      dashGapLength: 4,
                                      dashGapColor: Colors.white,
                                      dashColor: AppColors.grey_semi,
                                      dashLength: 2,
                                      lineThickness: 0.5,
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            Column(
                              children: List.generate(headings.length, (j) {
                                return Container(
                                  padding: EdgeInsets.symmetric(vertical: 7),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          headings[j],
                                          style: TextStyle(
                                            fontFamily: "JakartaRegular",
                                            fontSize: 14,
                                            color: AppColors.semi_black,
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: InkResponse(
                                          onTap: [
                                            "Attachment",
                                            "From Account",
                                            "Created Employee",
                                          ].contains(headings[j]) ? () {
                                            switch(headings[j]){
                                              case "Attachment":
                                                Navigator.push(
                                                  context,
                                                  MaterialPageRoute(
                                                    builder:
                                                        (context) => Fileviewer(
                                                      fileName:
                                                      payment_det
                                                          .attachmentViewFileName!,
                                                      fileUrl:
                                                      payment_det
                                                          .attachmentDirFilePath!,
                                                    ),
                                                  ),
                                                );
                                                break;
                                              case "From Account":
                                                Navigator.push(
                                                  context,
                                                  MaterialPageRoute(
                                                    builder:
                                                        (context) => Accountslistdetails(
                                                      accountID: payment_det.paymentAccountId,
                                                    ),
                                                  ),
                                                );
                                                break;
                                              case "Created Employee":
                                                Navigator.push(
                                                  context,
                                                  MaterialPageRoute(
                                                    builder:
                                                        (context) => Accountslistdetails(
                                                      accountID: payment_det.createdEmployeeId,
                                                    ),
                                                  ),
                                                );
                                                break;
                                            }

                                          } : null,
                                          child: Padding(
                                            padding: EdgeInsets.only(
                                              top: 2.5,
                                              bottom: 2.5,
                                            ),
                                            child: Text(
                                              subHeadings[j].isEmpty
                                                  ? "-"
                                                  : subHeadings[j],
                                              style: TextStyle(
                                                decoration:
                                                    [
                                                          "Attachment",
                                                          "From Account",
                                                          "Created Employee",
                                                        ].contains(headings[j])
                                                        ? TextDecoration
                                                            .underline
                                                        : TextDecoration.none,
                                                decorationStyle:
                                                    [
                                                          "From Account",
                                                          "Created Employee",
                                                        ].contains(headings[j])
                                                        ? TextDecorationStyle
                                                            .dotted
                                                        : subHeadings[j] ==
                                                            "View"
                                                        ? TextDecorationStyle
                                                            .solid
                                                        : TextDecorationStyle
                                                            .solid,
                                                decorationColor: [
                                                  "From Account",
                                                  "Created Employee",
                                                ].contains(headings[j])
                                                    ?  AppColors.grey_thick
                                                    : subHeadings[j] ==
                                                    "View"
                                                    ?  AppColors.app_blue
                                                    :  AppColors.app_blue,
                                                fontSize: 14,
                                                color:
                                                    subHeadings[j] == "View"
                                                        ? AppColors.app_blue
                                                        : Color(0xFF818181),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }),
                            ),
                          ],
                        );
                      }),
                    ),

                    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
                                  ? "Hide Details"
                                  : "View Details",
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                fontSize: 14,
                                color: AppColors.app_blue,
                              ),
                            ),
                            Transform.flip(
                              flipY: provider.showMoreDetails ? true : false,
                              child: SvgPicture.asset(
                                "assets/svg/arrow_dropdown.svg",
                                height: 25,
                                width: 20,
                                color: AppColors.app_blue,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _scaffold1(BuildContext context) {
    return Consumer<Paymentrequisitionpaymentslistprovider>(
      builder: (context, provider, child) {
        var payment_det = provider.paymentDetails;

        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar(context, widget.pageName),
          backgroundColor: AppColors.scaffold_bg_color,
          body: SizedBox(
            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(
                                  payment_det.accountName ?? "-",
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 14,
                                    color: AppColors.semi_black,
                                  ),
                                ),
                                Text(
                                  "₹${payment_det.amount}",
                                  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(
                                payment_det.refType ?? "-",
                                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) {
                      if (provider.Headings[j] == "Attachment" &&
                          payment_det.attachmentViewFileName == "") {
                        return SizedBox.shrink();
                      }
                      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] == "Attachment") {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Fileviewer(
                                              fileName:
                                                  payment_det
                                                      .attachmentViewFileName!,
                                              fileUrl:
                                                  payment_det
                                                      .attachmentDirFilePath!,
                                            ),
                                      ),
                                    );
                                  }
                                },
                                child: Text(
                                  provider.Headings[j] == "Attachment"
                                      ? "View"
                                      : provider.subHeadings[j] == ""
                                      ? "-"
                                      : provider.subHeadings[j] ?? "-",
                                  style: TextStyle(
                                    fontSize: 14,
                                    color:
                                        provider.Headings[j] == "Attachment"
                                            ? AppColors.app_blue
                                            : Color(0xFF818181),
                                    decoration:
                                        provider.Headings[j] == "Attachment"
                                            ? TextDecoration.underline
                                            : TextDecoration.none,
                                    decorationColor:
                                        provider.Headings[j] == "Attachment"
                                            ? AppColors.app_blue
                                            : AppColors.white,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    }),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
