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 '../../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? _dateError;

  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;
    notifyListeners();
  }

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

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

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

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

  set selectedCompetitor(String? value) {
    _selectedCompetitor = value;
    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;
    notifyListeners();
  }

  set dateError(value) {
    _dateError = 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,
    nextAppointmentStatus,
      orderStatus,
      leadID,
      followupType,
      competitor,
      leadStatus,
      appointmentType,
      sms,
      [mode]
  ) async {
    try {
      _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.toString() + ":" + _selectedTime.minute.toString(),
        latlongs,
        competitor,
        reasonController.text,
        leadStatus,
        nextAppointmentDateController.text,
        appointmentType,
        sms,
        noteController.text,
      );
      if (data != null && data.error == "0") {
        _submitLoading = false;
        resetForm();
        Navigator.pop(context);
        if(mode.isNotEmpty){
          prov2.crmLeadDetailsAPIFunction(context, leadID, mode);
        }

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

  void setDate(DateTime newDate) {
    _date = newDate;
    _formattedDate = 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.toString() + ":" + _selectedTime.minute.toString();
    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: 216,
            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: 1,
                    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: 3,
                    child: CupertinoDatePicker(
                      dateOrder: DatePickerDateOrder.dmy,
                      initialDateTime: _date ?? DateTime.now(),
                      mode: CupertinoDatePickerMode.date,
                      use24hFormat: true,
                      showDayOfWeek: true,
                      onDateTimeChanged: (DateTime newDate) {
                        setDate(newDate);
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }

  onFollowUpChanged(value) {}

  onNoteChanged(value) {}

  onReasonChanged(value) {}

  void resetForm(){
    nextAppointmentDateController.clear();
    followUpFeedbackController.clear();
    noteController.clear();
    reasonController.clear();
    _selectedFollowupType = null;
    _selectedLeadStatus = null;
    _nextAppointmentStatus = null;
    _selectNextAppointmentType = null;
    _selectOrderStatus = null;
    _selectedCompetitor = null;
    notifyListeners();
  }
}
