import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:grocery_app/src/core/network_services/service_locator.dart';
import 'package:grocery_app/src/data/address.dart';
import 'package:grocery_app/src/data/all_cart_items.dart';
import 'package:grocery_app/src/logic/repo/product_repo.dart';
import 'package:grocery_app/utils/extensions/extensions.dart';
import 'package:http/http.dart' as http;

class AddtocartProvider extends ChangeNotifier {
  String _pinCode = "Fetching...";
  bool _isLoading = false;
  bool _isDeliverable = false;

  String get pinCode => _pinCode;
  bool get isLoading => _isLoading;
  bool get isDeliverable => _isDeliverable;
  TextEditingController checkPinCode = TextEditingController();

  Future<void> getCurrentLocation(BuildContext context) async {
    _isLoading = true;
    notifyListeners();

    try {
      bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) {
        _isLoading = false;
        notifyListeners();

        return;
      }

      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
      );

      print("Location fetched: ${position.latitude}, ${position.longitude}");

      List<Placemark> placemarks = await placemarkFromCoordinates(
        position.latitude,
        position.longitude,
      );

      if (placemarks.isNotEmpty) {
        _pinCode = placemarks.first.postalCode ?? "Unknown";
        checkPinCode.text = _pinCode;
        print("Pincode found: $_pinCode");

        // Now check if this pin code is deliverable
        await checkPin(context, _pinCode);
      } else {
        _pinCode = "unable to current pi code";
        print("Error: No placemarks found.");
      }
    } catch (e) {
      _pinCode = "unable to current pi code";
      print("Error: ${e.toString()}");
    }
    _pinCode = "unable to current pi code";
    _isLoading = false;
    notifyListeners();
  }

  bool ischeckpin = false;
  Future<void> checkPin(BuildContext context, pin) async {
    ischeckpin = true;
    _pinCode = pin;
    notifyListeners();
    var data = {};
    try {
      var result = await _homeRepo.checkPin(data, pin);

      return result.fold(
        (error) {
          ischeckpin = false;
          _isDeliverable = false;
          isLoaddcartItem = false;
          notifyListeners();
        },
        (response) {
          if (response.isDeliverable!) {
            _isDeliverable = true;
          }
          ischeckpin = false;
          isLoaddcartItem = false;
          notifyListeners();
        },
      );
    } catch (e) {
      ischeckpin = false;
      _isDeliverable = false;
      isLoaddcartItem = false;
      notifyListeners();
    }
  }

  Map<String, bool> isRemoveItem = {};

  Future<void> deleteItem(BuildContext context, id) async {
    isRemoveItem[id] = true;
    notifyListeners();
    var data = {};
    try {
      var result = await _homeRepo.deleteItem(data, id);
      return result.fold(
        (error) {
          isRemoveItem[id] = false;
          notifyListeners();
        },
        (response) {
          getItemCards(context);
          isRemoveItem[id] = false;
          notifyListeners();
        },
      );
    } catch (e) {
      isRemoveItem[id] = false;

      notifyListeners();
    }
  }

  final _homeRepo = getIt<ProductRepo>();

  AllCartItems allitem = AllCartItems();

  bool isLoaddcartItem = true;
  Future<void> getItemCards(BuildContext context) async {
    isLoaddcartItem = true;
    notifyListeners();
    var data = {};
    try {
      var result = await _homeRepo.getItemCards(data);

      return result.fold(
        (error) {
          isLoaddcartItem = false;
          notifyListeners();
        },
        (response) {
          allitem = response!;
          isLoaddcartItem = false;
          notifyListeners();
        },
      );
    } catch (e) {
      print("sfddsfdfff");
      isLoaddcartItem = false;
      notifyListeners();
    }
  }

  /////////////////////////////////  address/////////////////////////
  List<Datum> addresslist = [];

  Future<void> getAddress(BuildContext context) async {
    var data = {};
    try {
      var result = await _homeRepo.getAddress(data);

      return result.fold(
        (error) {
          print("dsjfgkjhkdfgdkjfhg");

          notifyListeners();
        },
        (response) {
          addresslist = response.data!;
          if (response.data!.isNotEmpty) {
            _selectedAddress = addresslist.last.id ?? "";
          } else {
            _selectedAddress = "";
          }

          notifyListeners();
        },
      );
    } catch (e) {
      print("sfddsfdfff");

      notifyListeners();
    }
  }

  String _selectedAddress = "";

  String get selectedAddress => _selectedAddress;

  void selectAddress(String address) {
    _selectedAddress = address;
    notifyListeners();
  }

  Set<String> cartItems = {};
  Map<String, bool> isLoadings = {};

  bool isLoadingCart = false;
  bool iscardAdded = false;

  Future<void> addToCart(
      BuildContext context, String productId, int quantity) async {
    context.showLoader(show: true);

    isLoadingCart = true;
    isLoadings[productId] = true;
    notifyListeners();

    var data = {"productId": productId, "quantity": quantity};

    try {
      var result = await _homeRepo.addToCart(data);
      context.showLoader(
        show: false,
      );

      result.fold(
        (error) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(error.message),
              backgroundColor: Colors.red,
            ),
          );
        },
        (response) async {
          await getItemCards(context);
          cartItems.add(productId); // Add product to cart
          // Fluttertoast.showToast(
          //   msg: "Added to cart successfully!",
          //   toastLength: Toast.LENGTH_SHORT,
          //   gravity: ToastGravity.BOTTOM,
          //   backgroundColor: Colors.green,
          //   textColor: Colors.white,
          //   fontSize: 14.0,
          // );
          iscardAdded = true;
          notifyListeners(); // Update UI after adding to cart
        },
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Something went wrong"),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      isLoadingCart = false;
      isLoadings[productId] = false;
      notifyListeners(); // Ensure UI updates after operation
    }
  }

  Future<void> decreaseCartQuantity(
      BuildContext context, String itemId, int quantity) async {
    context.showLoader(show: true);

    isLoadingCart = true;

    notifyListeners();

    // var data = {"productId": productId, "quantity": quantity};

    final Map<String, dynamic> cartData = {
      "items": [
        {"itemId": itemId, "quantity": quantity}
      ]
    };

    try {
      var result = await _homeRepo.decreaseQuantity(cartData);
      context.showLoader(
        show: false,
      );

      result.fold(
        (error) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(error.message),
              backgroundColor: Colors.red,
            ),
          );
        },
        (response) async {
          await getItemCards(context);

          // Fluttertoast.showToast(
          //   msg: "Added to cart successfully!",
          //   toastLength: Toast.LENGTH_SHORT,
          //   gravity: ToastGravity.BOTTOM,
          //   backgroundColor: Colors.green,
          //   textColor: Colors.white,
          //   fontSize: 14.0,
          // );
          iscardAdded = true;
          notifyListeners(); // Update UI after adding to cart
        },
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Something went wrong"),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      isLoadingCart = false;

      notifyListeners(); // Ensure UI updates after operation
    }
  }
}
