import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/crmProvider/crmLeadDetailsProvider.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/screens/crm/AppointmentDetails.dart';
import 'package:generp/screens/crm/FollowUpDetails.dart';
import 'package:generp/screens/crm/QuotationDetails.dart';
import 'package:generp/screens/crm/contactDetails.dart';
import 'package:generp/screens/crm/editAccountDetails.dart';
import 'package:generp/screens/crm/productDetails.dart';
import 'package:provider/provider.dart';

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

class LeadDetailsByMode extends StatefulWidget {
  final mode;
  final pageTitleName;
  final leadId;

  const LeadDetailsByMode({
    super.key,
    required this.mode,
    required this.pageTitleName,
    required this.leadId,
  });

  @override
  State<LeadDetailsByMode> createState() => _LeadDetailsByModeState();
}

class _LeadDetailsByModeState extends State<LeadDetailsByMode> {
  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) {
      final provider = Provider.of<crmLeadDetailsProvider>(
        context,
        listen: false,
      );
      provider.crmLeadDetailsAPIFunction(context, widget.leadId, widget.mode);
    });
  }

  @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<crmLeadDetailsProvider>(
      builder: (context, provider, child) {
        var leadDetails = provider.leadDetails;

        var headings1 = [
          "Account Manager Name",
          "Account Created By",
          "Address",
          "Lead Status",
          "Last Followup Date",
        ];
        var subHeadings1 = [
          provider.accountDetails!.accManager ?? "-",
          provider.accountDetails!.owner ?? "-",
          provider.leadDetails!.address ?? "-",
          provider.leadDetails!.status ?? "-",
          provider.followupDetails.first!.fdate ?? "-",
        ];

        var headings2 = [
          "State",
          "District",
          "Sub Locality",
          "Source",
          "Reference",
          "Team",
          "Segment",
          "Lead Age",
        ];

        var subHeadings2 = [
          provider.accountDetails!.state ?? "-",
          provider.accountDetails!.district ?? "-",
          provider.accountDetails!.subLocality ?? "-",
          provider.accountDetails!.source ?? "-",
          provider.accountDetails!.reference ?? "-",
          provider.accountDetails!.team ?? "-",
          provider.accountDetails!.segment ?? "-",
          "${provider.leadDetails!.lage ?? "-"} days",
        ];

        var totalHeadings = [...headings1];
        var totalSubHeadings = [...subHeadings1];

        if (provider.showMoreDetails) {
          totalHeadings = [...headings1, ...headings2];
          totalSubHeadings = [...subHeadings1, ...subHeadings2];
        }

        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2(
            context,
            "Lead Details (${widget.mode})",
            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(0xFFE6F6FF),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: SvgPicture.asset(
                              "assets/svg/se_block_head.svg",
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          flex: 4,
                          child: SizedBox(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  leadDetails.name ?? "-",
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 14,
                                    color: AppColors.semi_black,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        if (provider.showEditButton == "1")
                          Expanded(
                            flex: 1,
                            child: InkResponse(
                              onTap: () async {
                                var res = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder:
                                        (context) => EditAccountDetails(
                                          leadID: leadDetails.id,
                                          mode: widget.mode,
                                          accountID: leadDetails.accId,
                                          companyName: leadDetails.name,
                                        ),
                                  ),
                                );
                                if (res == true) {
                                  provider.crmLeadDetailsAPIFunction(
                                    context,
                                    widget.leadId,
                                    widget.mode,
                                  );
                                }
                              },
                              child: Container(
                                height: 32,
                                width: 30,
                                padding: EdgeInsets.all(8.0),
                                child: SvgPicture.asset(
                                  "assets/svg/crm_contact_edit.svg",
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                    Divider(thickness: 0.5, color: Color(0xFFD7D7D7)),
                    ...List.generate(totalSubHeadings.length, (j) {
                      return Container(
                        padding: EdgeInsets.symmetric(vertical: 7),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              child: Text(
                                totalHeadings[j],
                                style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  fontSize: 14,
                                  color: AppColors.semi_black,
                                ),
                              ),
                            ),
                            Expanded(
                              child: InkResponse(
                                child:
                                    totalHeadings[j] == "Lead Age"
                                        ? Tooltip(
                                          triggerMode: TooltipTriggerMode.tap,

                                          message:
                                              "${provider.leadDetails.createdDatetime}",
                                          child: Text(
                                            totalSubHeadings[j] == ""
                                                ? "-"
                                                : totalSubHeadings[j],
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: Color(0xFF818181),
                                              decorationColor:
                                                  AppColors.grey_semi,
                                              decoration:
                                                  TextDecoration.underline,
                                            ),
                                          ),
                                        )
                                        : Text(
                                          totalSubHeadings[j] == ""
                                              ? "-"
                                              : totalSubHeadings[j],
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: 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
                                  ? "- Show Less"
                                  : "+ More Details",
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                fontSize: 14,
                                color: AppColors.app_blue,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  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<crmLeadDetailsProvider>(
                builder: (context, provider, child) {
                  final assetnames = [
                    "crm_appoint_details",
                    "crm_cont_details",
                    "crm_follow_up_details",
                    "crm_prod_details",
                    "crm_quotation_details",
                  ];

                  final Headingnames = [
                    "Product Details",
                    "Contact Details",
                    "Followup Details",
                    "Appointment Details",
                    "Quotation Details",
                  ];

                  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(assetnames.length, (index) {
                            return ListTile(
                              onTap: () {
                                Navigator.pop(context, true);
                                switch (index) {
                                  case 0:
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Productdetails(
                                              leadID: provider.leadDetails.id,
                                              mode: widget.mode,
                                            ),
                                      ),
                                    );
                                    break;
                                  case 1:
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Contactdetails(
                                              accID: provider.leadDetails.accId,
                                            ),
                                      ),
                                    );
                                    break;
                                  case 2:
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => FollowUpDetails(),
                                      ),
                                    );
                                    break;
                                  case 3:
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => AppointmentDetails(
                                              leadID: provider.leadDetails.id,
                                            ),
                                      ),
                                    );
                                    break;
                                  case 4:
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => QuotationDetails(
                                              leadID: provider.leadDetails.id,
                                              mode: widget.mode,
                                            ),
                                      ),
                                    );
                                  default:
                                    print("object");
                                }
                              },
                              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",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
