import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geolocator/geolocator.dart' as geo_location;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../../screens/crm/LeadDetailsByMode.dart';
import '../../screens/order/addOrder.dart';
import '../../services/api_calling.dart';
import 'crmLeadDetailsProvider.dart';

class followUpUpdateProvider extends ChangeNotifier {
  bool _submitLoading = false;
  TextEditingController nextAppointmentDateController = TextEditingController();
  TextEditingController followUpFeedbackController = TextEditingController();
  TextEditingController noteController = TextEditingController();
  TextEditingController reasonController = TextEditingController();

  TimeOfDay _selectedTime = TimeOfDay.now();
  String _formattedTime = "";

  String? _selectedFollowupType;
  String? _selectedLeadStatus;
  String? _nextAppointmentStatus;
  String? _selectNextAppointmentType;
  String? _selectOrderStatus;
  String? _selectedCompetitor;

  LatLng? currentLocationLatLng;
  String? latlongs;

  DateTime? _date;
  String? _formattedDate;
  String? _formattedDateToSend;
  String? _dateError;

  String? followupError;
  String? followupFeedbackError;
  String? leadStatusError;
  String? appStatusError;
  String? nextAppDateError;
  String? nextAppType;
  String? noteError;
  String? orderStatusError;
  String? competitorError;
  String? reasonError;

  String? get formattedDateToSend => _formattedDateToSend;

  bool get submitLoading => _submitLoading;

  TimeOfDay get selectedTime => _selectedTime;

  String get formattedTime => _formattedTime;

  String? get selectedFollowupType => _selectedFollowupType;

  String? get selectedLeadStatus => _selectedLeadStatus;

  String? get nextAppointmentStatus => _nextAppointmentStatus;

  String? get selectNextAppointmentType => _selectNextAppointmentType;

  String? get selectOrderStatus => _selectOrderStatus;

  String? get selectedCompetitor => _selectedCompetitor;

  set submitLoading(bool value) {
    _submitLoading = value;
    notifyListeners();
  }

  set selectedFollowupType(String? value) {
    _selectedFollowupType = value;
    followupError = null;
    notifyListeners();
  }

  set selectedLeadStatus(String? value) {
    _selectedLeadStatus = value;
    leadStatusError = null;
    notifyListeners();
  }

  set nextAppointmentStatus(String? value) {
    _nextAppointmentStatus = value;
    appStatusError = null;
    notifyListeners();
  }

  set selectNextAppointmentType(String? value) {
    _selectNextAppointmentType = value;
    nextAppType = null;
    notifyListeners();
  }

  set selectOrderStatus(String? value) {
    _selectOrderStatus = value;
    orderStatusError = null;
    notifyListeners();
  }

  set selectedCompetitor(String? value) {
    _selectedCompetitor = value;
    competitorError = null;
    notifyListeners();
  }

  bool _checked = false;
  var _smsSent = "0";

  bool get checked => _checked;

  get smsSent => _smsSent;

  set smsSent(value) {
    _smsSent = value;
    notifyListeners();
  }

  set checked(value) {
    _checked = value;
    notifyListeners();
  }

  set formattedDate(String? value) {
    _formattedDate = value;
    nextAppointmentDateController.text = _formattedDate!;
    _dateError = null;
    nextAppDateError = null;
    notifyListeners();
  }

  set dateError(value) {
    _dateError = value;
    nextAppDateError = value;
    notifyListeners();
  }

  Future<void> getCurrentLocation(context) async {
    try {
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: geo_location.LocationAccuracy.high,
      );
      currentLocationLatLng = LatLng(position.latitude, position.longitude);
      print("Current Loc: $currentLocationLatLng");
      latlongs = '${position.latitude},${position.longitude}';
      print("latlongs : $latlongs");
      notifyListeners();
    } catch (e) {
      print("Error getting current location: $e");
    }
  }

  Future<void> crmAddFollowUpAPIFunction(
      BuildContext context,
      fromScreen,
      nextAppointmentStatus,
      orderStatus,
      leadID,
      followupType,
      competitor,
      leadStatus,
      appointmentType,
      feedback,
      inTime,
      loc,
      sms, [
        mode,
      ]) async {
    try {
      // validate form before API call
      if (!valid()) {
        return;
      }

      _submitLoading = true;
      notifyListeners();

      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final prov2 = Provider.of<crmLeadDetailsProvider>(context, listen: false);

      final data = await ApiCalling.crmLeadDetailsAddFollowUpAPI(
        prov.session,
        prov.empId,
        nextAppointmentStatus,
        orderStatus,
        leadID,
        followUpFeedbackController.text,
        followupType,
        "${_selectedTime.hour}:${_selectedTime.minute}",
        latlongs,
        competitor,
        reasonController.text,
        leadStatus,
        _formattedDateToSend,
        appointmentType,
        sms,
        noteController.text,
      );

      debugPrint("status ================ $orderStatus");


      if (data != null && data.error == "0") {
        _submitLoading = false;

        resetForm();

        if (orderStatus == "Order Gain") {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (_) => AddorderScreen(
                key: UniqueKey(),
                mode: mode,
                pageTitleName: "Add Order",
                leadId: leadID,
                feedback: feedback,
                followupType: followupType,
                inTime: inTime,
                loc: loc,
              ),
            ),
          );
        } else if (fromScreen == "Pending Tasks") {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(
              builder: (_) => LeadDetailsByMode(
                mode: "executive",
                pageTitleName: "Lead Details",
                leadId: leadID ?? "-",
              ),
              settings: const RouteSettings(name: "LeadDetailsByMode"),
            ),
                (Route<dynamic> route) =>
            route.settings.name == 'CrmdashboardScreen',
          );
        } else {
          Navigator.pop(context);
        }

        if (mode.isNotEmpty) {
          prov2.crmLeadDetailsAPIFunction(context, leadID, mode);
        }

        notifyListeners();
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } catch (e, s) {
      _submitLoading = false;
      notifyListeners();
      debugPrint("Error: $e, Stack: $s");
    }
  }


  bool valid() {
    followupError = null;
    followupFeedbackError = null;
    leadStatusError = null;
    appStatusError = null;
    nextAppDateError = null;
    nextAppType = null;
    noteError = null;
    orderStatusError = null;
    competitorError = null;
    reasonError = null;
    bool isValid = true;
    if (_selectedFollowupType == null || _selectedFollowupType == "") {
      followupError = "Please select Followup Type";
      isValid = false;
    }
    if (followUpFeedbackController.text.trim().isEmpty) {
      followupFeedbackError = "Please enter Feedback";
      isValid = false;
    }
    if (_selectedLeadStatus == null || _selectedLeadStatus == "") {
      leadStatusError = "Please Select Lead Status";
      isValid = false;
    }
    if (_nextAppointmentStatus == null || _nextAppointmentStatus == "") {
      appStatusError = "Please select a value";
      isValid = false;
    }
    if (nextAppointmentStatus == "Next Appointment") {
      if (nextAppointmentDateController.text.trim().isEmpty) {
        nextAppDateError = "Please Enter Date";
        isValid = false;
      }

      if (_selectNextAppointmentType == null ||
          _selectNextAppointmentType == "") {
        nextAppType = "Please select Appointment Type";
        isValid = false;
      }

      if (noteController.text.trim().isEmpty) {
        noteError = "Enter Note";
        isValid = false;
      }
    } else if (nextAppointmentStatus == "Update Order Status") {
      if (_selectOrderStatus == null || _selectOrderStatus == "") {
        orderStatusError = "Please Select Order Status";
        isValid = false;
      }
      if (selectOrderStatus == "Order Lost") {
        if (_selectedCompetitor == null || _selectedCompetitor == "") {
          competitorError = "Please Select Competitor";
          isValid = false;
        }
      } else if (selectOrderStatus == "No Requirement") {
        if (reasonController.text.trim().isEmpty) {
          reasonError = "Please Enter reason";
          isValid = false;
        }
      }
    }
    _submitLoading = false;
    notifyListeners();
    return isValid;
  }

  void setDate(DateTime newDate) {
    _date = newDate;
    // _formattedDate = DateFormat('yyyy-MM-dd').format(newDate);
    _formattedDate = DateFormat('d MMM yyyy').format(newDate);
    _formattedDateToSend = DateFormat('yyyy-MM-dd').format(newDate);
    nextAppointmentDateController.text = _formattedDate!;
    _dateError = null;
    notifyListeners();
  }

  Future<void> selectTime(BuildContext context) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: _selectedTime,
    );
    if (picked != null && picked != _selectedTime) _selectedTime = picked;
    _formattedTime = "${_selectedTime.hour}:${_selectedTime.minute}";
    notifyListeners();
  }

  String formatTime(int hour, int minute) {
    String period = (hour >= 12) ? 'pm' : 'am';
    if (hour == 0) {
      hour = 12;
    } else if (hour > 12) {
      hour -= 12;
    }

    String formattedHour = (hour < 10) ? '0$hour' : '$hour';
    String formattedMinute = (minute < 10) ? '0$minute' : '$minute';

    print("formattedTime: $formattedHour:$formattedMinute $period");
    return '$formattedHour:$formattedMinute $period';
  }

  void showDatePickerDialog(BuildContext context) {
    showCupertinoModalPopup<void>(
      context: context,
      builder:
          (BuildContext context) => Container(
            height: 250,
            padding: const EdgeInsets.only(top: 6.0),
            margin: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            color: CupertinoColors.systemBackground.resolveFrom(context),
            child: SafeArea(
              top: false,
              child: Column(
                children: [
                  Expanded(
                    flex: 2,
                    child: SizedBox(
                      height: 40,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CupertinoButton(
                            child: Text(
                              'Cancel',
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                color: AppColors.app_blue,
                              ),
                            ),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoButton(
                            child: Text(
                              'Done',
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                color: AppColors.app_blue,
                              ),
                            ),
                            onPressed: () {
                              setDate(_date ?? DateTime.now());
                              Navigator.pop(context);
                            },
                          ),
                        ],
                      ),
                    ),
                  ),

                  Expanded(
                    flex: 4,
                    child: CupertinoDatePicker(
                      initialDateTime: _date ?? DateTime.now(),
                      minimumDate: DateTime(
                        DateTime.now().year,
                        DateTime.now().month,
                        DateTime.now().day,
                      ),
                      dateOrder: DatePickerDateOrder.dmy,
                      mode: CupertinoDatePickerMode.date,
                      use24hFormat: true,
                      showDayOfWeek: true,
                      onDateTimeChanged: (DateTime newDate) {
                        setDate(newDate);
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }

  onFollowUpChanged(value) {
    followupFeedbackError = null;
    notifyListeners();
  }

  onNoteChanged(value) {
    noteError = null;
    notifyListeners();
  }

  onReasonChanged(value) {
    reasonError = null;
    notifyListeners();
  }

  void resetForm() {
    nextAppointmentDateController.clear();
    _formattedDateToSend = null;
    _formattedDate = null;
    _date = null;

    followUpFeedbackController.clear();
    noteController.clear();
    reasonController.clear();
    _selectedFollowupType = null;
    _selectedLeadStatus = null;
    _nextAppointmentStatus = null;
    _selectNextAppointmentType = null;
    _selectOrderStatus = null;
    _selectedCompetitor = null;
    followupError = null;
    followupFeedbackError = null;
    leadStatusError = null;
    appStatusError = null;
    nextAppDateError = null;
    nextAppType = null;
    noteError = null;
    orderStatusError = null;
    competitorError = null;
    reasonError = null;
    notifyListeners();
  }
}
