import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/crmModels/crmDashboardResponse.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../../Models/crmModels/AccessiblePagesResponse.dart';
import '../../Models/crmModels/crmPendingTasksResponse.dart';
import '../../Models/crmModels/crmUniversalSearchResponse.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class Crmdashboardprovider extends ChangeNotifier {
  TextEditingController nextAppointmentDateController = TextEditingController();
  TextEditingController searchController = TextEditingController();
  List<PagesAccessible> _accessPages = [];

  List<PagesAccessible> get accessPages => _accessPages;
  List<PendingTasks> _pendingTasks = [];

  List<PendingTasks> get pendingTasksLists => _pendingTasks;
  List<Accounts> _accountsList = [];
  List<Leads> _leadsList = [];
  List<Enquires> _enquiresList = [];
  TimeOfDay _selectedTime = TimeOfDay.now();
  String _formattedTime = "";

  String? _selectedFollowupType;
  String? _selectedLeadStatus;
  String? _nextAppointmentStatus;
  String? _selectNextAppointmentType;

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


  TimeOfDay get selectedTime => _selectedTime;
  String get formattedTime => _formattedTime;

  String? get selectedFollowupType => _selectedFollowupType;
  String? get selectedLeadStatus => _selectedLeadStatus;
  String? get nextAppointmentStatus => _nextAppointmentStatus;
  String? get selectNextAppointmentType => _selectNextAppointmentType;

  List<Accounts> get accountsList => _accountsList;

  List<Leads> get leadsList => _leadsList;

  List<Enquires> get enquiresList => _enquiresList;

  Hotleads _hotleads = Hotleads();

  Hotleads get hotleads => _hotleads;
  Hotleads _coldleads = Hotleads();

  Hotleads get coldleads => _coldleads;
  Hotleads _warmleads = Hotleads();

  Hotleads get warmleads => _warmleads;
  Hotleads _totalleads = Hotleads();

  Hotleads get totalleads => _totalleads;
  Hotleads _orderlost = Hotleads();

  Hotleads get orderlost => _orderlost;
  Hotleads _norequirement = Hotleads();

  Hotleads get norequirement => _norequirement;
  Hotleads _openEnquiries = Hotleads();

  Hotleads get openEnquiries => _openEnquiries;

  List<Hotleads> _allLeads = [];

  List<Hotleads> get allLeads => _allLeads;

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

  Future<void> accessPagesAPIFunction(context) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmAccessiblePagesAPI(
        HomeProv.empId,
        HomeProv.session,
      );
      if (data != null) {
        if (data.error == "0") {
          _accessPages = data.pagesAccessible!;
          _accessPages.add(
            PagesAccessible(mode: "", id: 0, pageName: "Nearby Leads"),
          );
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  Future<void> crmDashboardAPIFunction(
    context,
    mode,
    from,
    to,
    teamemployee,
  ) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmDashboardAPI(
        HomeProv.empId,
        HomeProv.session,
        mode,
        from,
        to,
        teamemployee,
      );
      if (data != null) {
        if (data.error == "0") {
          _hotleads = data.hotleads!;
          _coldleads = data.coldleads!;
          _warmleads = data.warmleads!;
          _totalleads = data.totalleads!;
          _orderlost = data.orderlost!;
          _norequirement = data.norequirement!;
          _openEnquiries = data.openEnquiries!;
          _allLeads = [
            _hotleads,
            _coldleads,
            _warmleads,
            _totalleads,
            _orderlost,
            _norequirement,
            _openEnquiries,
          ];
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  Future<void> crmPendingTasksAPIFunction(context) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmPendingTasksAPI(
        HomeProv.empId,
        HomeProv.session,
      );
      if (data != null) {
        if (data.error == "0") {
          _pendingTasks = data.pendingTasks!;
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  Future<void> crmUniversalSearchFunction(context) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmUniversalSearchAPI(
        HomeProv.empId,
        HomeProv.session,
        searchController.text,
      );
      if (data != null) {
        if (data.error == "0") {
          _accountsList = data.accounts ?? [];
          _leadsList = data.leads ?? [];
          _enquiresList = data.enquires ?? [];
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

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

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

  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: () {
                          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);
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

}
