import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:generp/Notifiers/crmProvider/followUpUpdateProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:provider/provider.dart';

class Followupupdatescreen extends StatefulWidget {
  final leadID;
  final mode;
  final from;
  const Followupupdatescreen({super.key,required this.leadID, this.mode, this.from});

  @override
  State<Followupupdatescreen> createState() => _FollowupupdatescreenState();
}

class _FollowupupdatescreenState extends State<Followupupdatescreen> {
  Dropdowntheme ddtheme = Dropdowntheme();
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;


  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((event) {
      setState(() => _source = event);
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<followUpUpdateProvider>(context,listen: false);
      provider.getCurrentLocation(context);
    });
  }

  @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<followUpUpdateProvider>(
      builder: (context, provider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.scaffold_bg_color,
          appBar: AppBar(
            automaticallyImplyLeading: false,
            // elevation: 2.0,
            title: SizedBox(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: SvgPicture.asset(
                      "assets/svg/appbar_back_button.svg",
                      height: 25,
                    ),
                  ),
                  SizedBox(width: 10),
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: Text(
                      "Followup Update",
                      style: TextStyle(
                        fontSize: 16,
                        height: 1.1,
                        fontFamily: "JakartaSemiBold",
                        color: AppColors.semi_black,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          body: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.only(left: 10,top: 10),
                  alignment: Alignment.topLeft,
                  child: Text(
                    "Follow up Details",
                    style: TextStyle(color: AppColors.grey_thick, fontSize: 16),
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      TextWidget(context, "In Time"),
                      Container(
                        decoration: BoxDecoration(
                          color: AppColors.text_field_color,
                          borderRadius: BorderRadius.circular(14),
                        ),
                        child: InkWell(
                          onTap: () {
                            provider.selectTime(context);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            height: 45,
                            margin: EdgeInsets.only(left: 15.0, right: 15.0),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(15.0),
                            ),
                            child: Row(
                              children: [
                                Text(
                                  provider.selectedTime.hour.toString() +
                                      ":" +
                                      provider.selectedTime.minute
                                          .toString() ??
                                      "Enter in Time",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(fontWeight: FontWeight.w400),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      TextWidget(context, "Follow up Type"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                hint: const Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        'Select Followup Type',
                                        style: TextStyle(fontSize: 14),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                items:
                                <String>['Phone', 'Visit']
                                    .map(
                                      (value) =>
                                      DropdownMenuItem<String>(
                                        value: value,
                                        child: Text(
                                          value ?? '',
                                          style: const TextStyle(
                                            fontSize: 14,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                )
                                    .toList(),
                                value: provider.selectedFollowupType,
                                onChanged: (String? newValue) {
                                  setState(() {
                                    provider.selectedFollowupType = newValue!;
                                  });
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      if(provider.followupError!=null)...[
                        errorWidget(context, provider.followupError)
                      ],
                      textControllerWidget(
                        context,
                        provider.followUpFeedbackController,
                        "Feedback",
                        "Write Feedback",
                        provider.onFollowUpChanged,
                        TextInputType.text,
                        false,
                        null,
                      ),
                      if(provider.followupFeedbackError!=null)...[
                        errorWidget(context, provider.followupFeedbackError)
                      ],
                      TextWidget(context, "Lead Status"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                hint: const Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        'Select Lead Status',
                                        style: TextStyle(fontSize: 14),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                items:
                                <String>['All','Cold', 'Hot', 'Warm']
                                    .map(
                                      (value) =>
                                      DropdownMenuItem<String>(
                                        value: value,
                                        child: Text(
                                          value ?? '',
                                          style: const TextStyle(
                                            fontSize: 14,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                )
                                    .toList(),
                                value: provider.selectedLeadStatus,
                                onChanged: (String? newValue) {
                                  setState(() {
                                    provider.selectedLeadStatus = newValue!;
                                  });
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      if(provider.leadStatusError!=null)...[
                        errorWidget(context, provider.leadStatusError)
                      ],
                      TextWidget(
                        context,
                        "Next Appointment/Update Order Status",
                      ),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                hint: const Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        'Select Status',
                                        style: TextStyle(fontSize: 14),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                items:
                                <String>[
                                  'Next Appointment',
                                  'Update Order Status',
                                ]
                                    .map(
                                      (value) =>
                                      DropdownMenuItem<String>(
                                        value: value,
                                        child: Text(
                                          value ?? '',
                                          style: const TextStyle(
                                            fontSize: 14,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                )
                                    .toList(),
                                value: provider.nextAppointmentStatus,
                                onChanged: (String? newValue) {
                                  setState(() {
                                    provider.nextAppointmentStatus = newValue!;
                                  });
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      if(provider.appStatusError!=null)...[
                        errorWidget(context, provider.appStatusError)
                      ]
                    ],
                  ),
                ),
                SizedBox(height: 15),
                if (provider.nextAppointmentStatus ==
                    "Update Order Status") ...[
                  Container(
                    padding: EdgeInsets.only(left: 10),
                    alignment: Alignment.topLeft,
                    child: Text(
                      "Update Order Status",
                      style: TextStyle(
                        color: AppColors.grey_thick,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(15),
                    ),
                    margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        TextWidget(context, "Select Status"),
                        DropdownButtonHideUnderline(
                          child: Row(
                            children: [
                              Expanded(
                                child: DropdownButton2<String>(
                                  isExpanded: true,
                                  hint: const Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          'Select Status',
                                          style: TextStyle(fontSize: 14),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ],
                                  ),
                                  items:
                                  <String>[
                                    // 'Order Gain',
                                    'Order Lost',
                                    'No Requirement',
                                  ]
                                      .map(
                                        (value) =>
                                        DropdownMenuItem<String>(
                                          value: value,
                                          child: Text(
                                            value ?? '',
                                            style: const TextStyle(
                                              fontSize: 14,
                                            ),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                  )
                                      .toList(),
                                  value: provider.selectOrderStatus,
                                  onChanged: (String? newValue) {
                                    setState(() {
                                      provider.selectOrderStatus = newValue!;
                                    });
                                  },
                                  buttonStyleData: ddtheme.buttonStyleData,
                                  iconStyleData: ddtheme.iconStyleData,
                                  menuItemStyleData: ddtheme.menuItemStyleData,
                                  dropdownStyleData: ddtheme.dropdownStyleData,
                                ),
                              ),
                            ],
                          ),
                        ),
                        if(provider.orderStatusError!=null)...[
                          errorWidget(context, provider.orderStatusError)
                        ],
                        if (provider.selectOrderStatus == "Order Gain")
                          ...[]
                        else
                          ...[
                            if (provider.selectOrderStatus == "Order Lost") ...[
                              TextWidget(context, "Select Competitor"),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<String>(
                                        isExpanded: true,
                                        hint: const Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                'Select Competitor',
                                                style: TextStyle(fontSize: 14),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                          ],
                                        ),
                                        items:
                                        <String>[
                                          "Mahindra",
                                          "Kirloskar",
                                          "Cummins",
                                          "Ashok Leyland",
                                          "Escorts",
                                          "Eicher",
                                          "Eicher Volovo",
                                          "Ecogen",
                                          "Crompton Greaves",
                                          "Caterpillar",
                                        ]
                                            .map(
                                              (value) =>
                                              DropdownMenuItem<String>(
                                                value: value,
                                                child: Text(
                                                  value ?? '',
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                  overflow:
                                                  TextOverflow
                                                      .ellipsis,
                                                ),
                                              ),
                                        )
                                            .toList(),
                                        value: provider.selectedCompetitor,
                                        onChanged: (String? newValue) {
                                          setState(() {
                                            provider.selectedCompetitor =
                                            newValue!;
                                          });
                                        },
                                        buttonStyleData: ddtheme
                                            .buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              if(provider.competitorError!=null)...[
                                errorWidget(context, provider.competitorError)
                              ]
                            ] else
                              if (provider.selectOrderStatus ==
                                  "No Requirement")
                                ...[],
                            textControllerWidget(
                              context,
                              provider.reasonController,
                              "Reason",
                              "Reason (Description)",
                              provider.onReasonChanged,
                              TextInputType.text,
                              false,
                              null,
                            ),
                            if(provider.reasonError!=null)...[
                              errorWidget(context, provider.reasonError)
                            ]
                          ],
                      ],
                    ),
                  ),
                  SizedBox(height: 25),
                ] else if(provider.nextAppointmentStatus ==
                    "Next Appointment")
                  ...[
                    Container(
                      padding: EdgeInsets.only(left: 10),
                      alignment: Alignment.topLeft,
                      child: Text(
                        "Next Appointment",
                        style: TextStyle(
                          color: AppColors.grey_thick,
                          fontSize: 16,
                        ),
                      ),
                    ),
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15),
                      ),
                      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                      padding: EdgeInsets.symmetric(
                          horizontal: 10, vertical: 5),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          TextWidget(context, "Next Appointment Date"),
                          GestureDetector(
                            onTap: () {
                              provider.showDatePickerDialog(context);
                            },
                            child: Container(
                              height: 50,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(
                                  10.0,
                                  0.0,
                                  10,
                                  0,
                                ),
                                child: TextFormField(
                                  controller:
                                  provider.nextAppointmentDateController,
                                  keyboardType: TextInputType.text,
                                  enabled: false,
                                  maxLines: 1,
                                  readOnly: true,
                                  onChanged: (value) {},
                                  decoration: InputDecoration(
                                    hintText: "Enter Date",
                                    hintStyle: TextStyle(
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xFFB4BEC0),
                                      fontSize: 14,
                                    ),

                                    enabledBorder: InputBorder.none,
                                    disabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          if(provider.nextAppDateError!=null)...[
                            errorWidget(context, provider.nextAppDateError)
                          ],
                          TextWidget(context, "Appointment Type"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    isExpanded: true,
                                    hint: const Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            'Select Appointment Type',
                                            style: TextStyle(fontSize: 14),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                    items:
                                    <String>['Phone', 'Visit']
                                        .map(
                                          (value) =>
                                          DropdownMenuItem<String>(
                                            value: value,
                                            child: Text(
                                              value ?? '',
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                    )
                                        .toList(),
                                    value: provider.selectNextAppointmentType,
                                    onChanged: (String? newValue) {
                                      setState(() {
                                        provider.selectNextAppointmentType =
                                        newValue!;
                                      });
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData: ddtheme
                                        .menuItemStyleData,
                                    dropdownStyleData: ddtheme
                                        .dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          if(provider.nextAppType!=null)...[
                            errorWidget(context, provider.nextAppType)
                          ],

                          if (provider.selectNextAppointmentType ==
                              "Visit") ...[
                            CheckboxListTile(
                              activeColor: AppColors.app_blue,
                              checkboxShape: CircleBorder(),
                              controlAffinity: ListTileControlAffinity.leading,
                              value: provider.checked,
                              contentPadding: EdgeInsets.symmetric(
                                  horizontal: 0),
                              title: Text(
                                "Send SMS reminder to Customer",
                                style: TextStyle(
                                  fontSize: 14,
                                  fontFamily: "JakartaRegular",
                                ),
                              ),
                              onChanged: (value) {
                                provider.checked = !provider.checked;
                                if (value == true) {
                                  provider.smsSent = "1";
                                } else {
                                  provider.smsSent = "0";
                                }
                                print(provider.smsSent +
                                    provider.checked.toString());
                              },
                            ),
                          ],
                          textControllerWidget(
                            context,
                            provider.noteController,
                            "Note",
                            "Write Note",
                            provider.onNoteChanged,
                            TextInputType.text,
                            false,
                            null,
                          ),
                          if(provider.noteError!=null)...[
                            errorWidget(context, provider.noteError)
                          ],
                        ],
                      ),
                    ),
                    SizedBox(height: 25),
                  ],
                SizedBox(height: 150),
              ],
            ),
          ),
          floatingActionButtonLocation:
          FloatingActionButtonLocation.centerFloat,
          floatingActionButton: InkResponse(
            onTap:provider.submitLoading?null: () {
              provider.submitLoading = true;
              provider.crmAddFollowUpAPIFunction(
                  context,
                  widget.from,
                  provider.nextAppointmentStatus,
                  provider.selectOrderStatus,
                  widget.leadID,
                  provider.selectedFollowupType,
                  provider.selectedCompetitor,
                  provider.selectedLeadStatus,
                  provider.selectNextAppointmentType,
                  provider.smsSent,
              widget.mode);
            },
            child: Container(
              height: 45,
              alignment: Alignment.center,
              margin: EdgeInsets.symmetric(horizontal: 10),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              decoration: BoxDecoration(
                color: AppColors.app_blue,
                borderRadius: BorderRadius.circular(15),
              ),
              child:provider.submitLoading?CircularProgressIndicator.adaptive(
                valueColor: AlwaysStoppedAnimation(AppColors.white),
              ): Text(
                "Submit",
                style: TextStyle(
                  fontSize: 15,
                  fontFamily: "JakartaMedium",
                  color: Colors.white,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
