import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/crmProvider/crmProspectDetailsProvider.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:provider/provider.dart';

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

class ProspectContactDetails extends StatefulWidget {
  final accountId;
  const ProspectContactDetails({super.key, required this.accountId});

  @override
  State<ProspectContactDetails> createState() => _ProspectContactDetailsState();
}

class _ProspectContactDetailsState extends State<ProspectContactDetails> {
  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) {});
  }

  @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<crmProspectDetailsProvider>(
      builder: (context, provider, child) {
        var customerDetails = provider.contactList;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar(context, "Contact Details"),
          backgroundColor: AppColors.scaffold_bg_color,
          body: SizedBox(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // TextWidget(context, "Contact Details"),
                  ListView.builder(
                    itemCount: customerDetails.length,
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      return Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 5,
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 15,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          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/crm_contact_profile.svg",
                                    ),
                                  ),
                                ),
                                SizedBox(width: 10),
                                Expanded(
                                  flex: 4,
                                  child: SizedBox(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          customerDetails[index].name ?? "-",
                                          style: TextStyle(
                                            fontFamily: "JakartaMedium",
                                            fontSize: 14,
                                            color: AppColors.semi_black,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                SizedBox(width: 10),
                                Expanded(
                                  flex: 1,
                                  child: InkResponse(
                                    onTap: () {
                                      provider.editNameController.text =
                                          customerDetails[index].name ?? "";
                                      provider.editDesignationController.text =
                                          customerDetails[index].designation ??
                                          "";
                                      provider.editMobileNumberController.text =
                                          customerDetails[index].mob1 ?? "";
                                      provider
                                              .editAlternativeMobileController
                                              .text =
                                          customerDetails[index].mob2 ?? "";
                                      provider.editTelephoneController.text =
                                          customerDetails[index].tel ?? "";
                                      provider.editEmailController.text =
                                          customerDetails[index].email ?? "";
                                      _showEditContactSheet(
                                        context,
                                        index,
                                        provider.accountDetails.id!,
                                      );
                                    },
                                    child: Container(
                                      height: 35,
                                      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(5, (j) {
                              final textheads = [
                                "Mobile",
                                "Alternate Mobile",
                                "Telephone Number",
                                "Email",
                                "Designation",
                              ];
                              final textSubheads = [
                                customerDetails[index].mob1 ?? "-",
                                customerDetails[index].mob2 ?? "-",
                                customerDetails[index].tel ?? "-",
                                customerDetails[index].email ?? "-",
                                customerDetails[index].designation ?? "-",
                              ];
                              return Container(
                                padding: EdgeInsets.symmetric(
                                  vertical: 6,
                                  horizontal: 0,
                                ),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Expanded(
                                      child: Text(
                                        textheads[j].toString(),
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                    Expanded(
                                      child: Text(
                                        textSubheads[j] == ""
                                            ? "-"
                                            : textSubheads[j],
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          color: Color(0xFF818181),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            }),
                          ],
                        ),
                      );
                    },
                  ),

                  SizedBox(height: 75),
                ],
              ),
            ),
          ),
          floatingActionButton: Align(
            alignment: Alignment.bottomCenter,
            child: InkWell(
              onTap: () {
                _showAddContactSheet(context, provider.accountDetails.id!);
              },
              child: Container(
                alignment: Alignment.bottomCenter,
                height: 45,
                width: MediaQuery.of(context).size.width,
                margin: EdgeInsets.symmetric(horizontal: 10),
                decoration: BoxDecoration(
                  color: AppColors.app_blue,
                  borderRadius: BorderRadius.circular(14.0),
                ),
                child: Center(
                  child: Text(
                    "Add Contact",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontFamily: "JakartaMedium",
                    ),
                  ),
                ),
              ),
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
        );
      },
    );
  }

  Future<void> _showAddContactSheet(BuildContext context, accID) {
    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<crmProspectDetailsProvider>(
                builder: (context, provider, 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(
                              "Add Contact",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                              ),
                            ),
                          ),
                          textControllerWidget(
                            context,
                            provider.nameController,
                            "Name",
                            "Enter Name",
                            provider.onChangeName,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.nameError),
                          textControllerWidget(
                            context,
                            provider.designationController,
                            "Designation",
                            "Enter Designation",
                            provider.onChangeDesignation,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.designationError),
                          textControllerWidget(
                            context,
                            provider.mobileNumberController,
                            "Mobile Number",
                            "Enter Mobile Number",
                            provider.onChangeMobile,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.mobileNumError),
                          textControllerWidget(
                            context,
                            provider.alternativeMobileController,
                            "Alternative Mobile Number",
                            "Enter Alternative Mobile Number",
                            provider.onChangeAltMobile,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.altMobError),
                          textControllerWidget(
                            context,
                            provider.telephoneController,
                            "Telephone Number",
                            "Enter Telephone Number",
                            provider.onChangeTelephone,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.teleError),
                          textControllerWidget(
                            context,
                            provider.emailController,
                            "Email ID",
                            "Enter Email ID",
                            provider.onChangeEmailId,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.emailError),
                          InkWell(
                            onTap:
                                provider.isLoading
                                    ? null
                                    : () {
                                      provider.isLoading = true;
                                      provider
                                          .crmProspectDetailsAddContactAPIFunction(
                                            context,
                                            accID,
                                          );
                                    },
                            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:
                                    provider.isLoading
                                        ? CircularProgressIndicator.adaptive(
                                          valueColor: AlwaysStoppedAnimation(
                                            AppColors.white,
                                          ),
                                        )
                                        : Text(
                                          "Submit",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(color: Colors.white),
                                        ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }

  Future<void> _showEditContactSheet(BuildContext context, index, accid) {
    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<crmProspectDetailsProvider>(
                builder: (context, provider, 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(
                              "Edit Contact",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                              ),
                            ),
                          ),
                          textControllerWidget(
                            context,
                            provider.editNameController,
                            "Name",
                            "Enter Name",
                            provider.onChangeEditName,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.editNameError),
                          textControllerWidget(
                            context,
                            provider.editDesignationController,
                            "Designation",
                            "Enter Designation",
                            provider.onChangeEditDesignation,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.editDesignationError),
                          textControllerWidget(
                            context,
                            provider.editMobileNumberController,
                            "Mobile Number",
                            "Enter Mobile Number",
                            provider.onChangeEditMobile,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.editMobileNumError),

                          textControllerWidget(
                            context,
                            provider.editAlternativeMobileController,
                            "Alternative Mobile Number",
                            "Enter Alternative Mobile Number",
                            provider.onChangeEditAltMobile,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.editAltMobError),
                          textControllerWidget(
                            context,
                            provider.editTelephoneController,
                            "Telephone Number",
                            "Enter Telephone Number",
                            provider.onChangeEditTelephone,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.editTeleError),

                          textControllerWidget(
                            context,
                            provider.editEmailController,
                            "Email ID",
                            "Enter Email ID",
                            provider.onChangeEditEmailId,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.editEmailError),

                          InkWell(
                            onTap:
                                provider.isLoading
                                    ? null
                                    : () {
                                      provider.isLoading = true;
                                      provider
                                          .crmProspectDetailsEditContactAPIFunction(
                                            context,
                                            provider.contactList[index].id,
                                            accid,
                                          );
                                    },
                            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:
                                    provider.isLoading
                                        ? CircularProgressIndicator.adaptive(
                                          valueColor: AlwaysStoppedAnimation(
                                            AppColors.white,
                                          ),
                                        )
                                        : Text(
                                          "Submit",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(color: Colors.white),
                                        ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
