import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/crmModels/crmDashboardFollowUpResponse.dart';
import 'package:generp/Models/crmModels/crmDashboardQuotationResponse.dart';
import 'package:generp/Models/crmModels/crmDashboardResponse.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonServices.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 '../../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 {
  String _googleApikey = "AIzaSyBGzvgMMKwPBAANTwaoRsAnrCpiWCj8wVs";
  TextEditingController searchController = TextEditingController();
  List<PagesAccessible> _accessPages = [];

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

  List<PendingTasks> get pendingTasksLists => _pendingTasksList;
  List<Accounts> _accountsList = [];
  List<Leads> _leadsList = [];
  List<Enquires> _enquiresList = [];


  List<FollowupLists> _dashboardFollowUps = [];
  List<QuotationLists> _dashboardQuotations = [];

  List<FollowupLists>  get dashboardFollowUps => _dashboardFollowUps;
  List<QuotationLists> get dashboardQuotations => _dashboardQuotations;

  LatLng? currentLocationLatLng;
  String latlongs = "";

  List<Accounts> get accountsList => _accountsList;

  List<Leads> get leadsList => _leadsList;

  List<Enquires> get enquiresList => _enquiresList;

  List<NearbyLeads> _nearByLeads = [];

  List<NearbyLeads> get nearByLeads => _nearByLeads;

  Hotleads _hotleads = Hotleads();

  Hotleads get hotleads => _hotleads;

  Hotleads _pendingTasks = Hotleads();

  Hotleads get pendingTasks => _pendingTasks;

  Hotleads _coldleads = Hotleads();

  Hotleads get coldleads => _coldleads;

  Hotleads _warmleads = Hotleads();

  Hotleads get warmleads => _warmleads;

  Hotleads _totalleads = Hotleads();

  Hotleads get totalleads => _totalleads;

  Hotleads _openleads = Hotleads();

  Hotleads get openleads => _openleads;

  Hotleads _visits = Hotleads();

  Hotleads get visits => _visits;

  Hotleads _calls = Hotleads();

  Hotleads get calls => _calls;

  Hotleads _quote = Hotleads();

  Hotleads get quote => _quote;

  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;



  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> 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();
      crmDashboardAPIFunction(context);
    } catch (e) {
      print("Error getting current location: $e");
    }
  }

  Future<void> crmDashboardAPIFunction(context) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmDashboardAPI(
        HomeProv.empId,
        HomeProv.session,
        latlongs,
      );
      if (data != null) {
        if (data.error == "0") {
          _hotleads = data.hotleads!;
          _pendingTasks = data.pendingTasks!;
          _coldleads = data.coldleads!;
          _warmleads = data.warmleads!;
          _totalleads = data.totalleads!;
          _openleads = data.openleads!;
          _visits = data.visits!;
          _calls = data.calls!;
          _quote = data.quote!;
          _orderlost = data.orderlost!;
          _norequirement = data.norequirement!;
          _openEnquiries = data.openEnquiries!;
          _allLeads = [
            _openleads,
            _quote,
            _pendingTasks,
            _visits,
            _calls,
            _hotleads,
            _coldleads,
            _warmleads,
          ];
          _nearByLeads = data.nearbyLeads!;
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  String getStaticMapUrl(double lat, double lng) {
    const apiKey = 'YOUR_GOOGLE_MAPS_API_KEY';
    const zoom = 15;
    const size = '400x400';
    return 'https://maps.googleapis.com/maps/api/staticmap?center=$lat,$lng&zoom=$zoom&size=$size&key=$_googleApikey';
  }

  String getSimpleOSMImage(double lat, double lng) {
    final zoom = 15;
    //https://maps.googleapis.com/maps/api/staticmap?center=15.4919328,80.0492584&zoom=15&size=400x400
    return 'https://static-maps.yandex.ru/1.x/?ll=$lng,$lat&z=$zoom&size=400,400&l=map&pt=$lng,$lat,pm2rdm';
  }

  ({double lat, double lng}) parseLocation(String loc) {
    final parts = loc.split(',');
    return (
      lat: double.parse(parts[0].trim()),
      lng: double.parse(parts[1].trim()),
    );
  }

  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") {
          _pendingTasksList = 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) {}
  }

  Future<void> crmDashboardFollowUpAPIFunction(context,type) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmDashboardFollowUpAPI(
        HomeProv.empId,
        HomeProv.session,
          type
      );
      if (data != null) {
        if(data.sessionExists==1){
          if (data.error == "0") {
            _dashboardFollowUps = data.followupLists!;
            notifyListeners();
          }
        }else{
          sessionDoesNotExist(context);
        }

      }
    } catch (e, s) {}
  }
  Future<void> crmDashboardQuotationsAPIFunction(context) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmDashboardQuotationsAPI(
        HomeProv.empId,
        HomeProv.session,
      );
      if (data != null) {
        if(data.sessionExists==1){
          if (data.error == "0") {
           _dashboardQuotations = data.quotationLists!;
            notifyListeners();
          }
        }else{
          sessionDoesNotExist(context);
        }

      }
    } catch (e, s) {}
  }

}
