import 'dart:convert';

import 'package:cheminova/controller/home_controller.dart';
import 'package:cheminova/screens/authentication/controller/auth_service.dart';
import 'package:cheminova/screens/home_screen.dart';
import 'package:cheminova/utils/show_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../notification_service.dart';
import '../../../utils/api_client.dart';
import '../../../utils/api_urls.dart';
import '../../../utils/secure__storage_service.dart';

class AuthController extends GetxController {
  final authService = AuthService();

  final _apiClient = ApiClient();
  final _storageService = SecureStorageService();

  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  //TextEditingController phoneController = TextEditingController();
  TextEditingController currentpassController = TextEditingController();
  TextEditingController newpassController = TextEditingController();
  TextEditingController confirmpassController = TextEditingController();
  final HomeController _homeController = Get.put(HomeController());

  RxBool isLoading = false.obs;
  @override
  void onInit(){
    super.onInit();
     NotificationServices().requestNotificationPermission();
   }
  Future<void> login() async {
    isLoading.value = true;
    final response = await authService.login({
      'email': emailController.text,
      'password': passwordController.text,
    });
    isLoading.value = false;
    update();
    if (response != null) {
      _homeController.fcmToken();
      showSnackbar("Your Successfully logged In!");

      Get.offAll(() => const HomeScreen());
    }
    else if(response == null){
      showSnackbar("Please Enter Valid Email or Password");
    }
  }

  // Future<(bool, String)> login() async {
  //   isLoading(true);
  //   try {
  //     Response response = (await _apiClient.post(
  //       ApiUrls.loginUrl,
  //       data: {
  //         'email': emailController.text,
  //         'password': passwordController.text
  //       },
  //     )) as Response;
  //
  //     isLoading(false);
  //
  //     // Check if the response status code is 200
  //     if (response.statusCode == 200) {
  //       // Access the data field from the response
  //       final responseData = jsonDecode(response.body) as Map<String, dynamic>;
  //       final token = responseData['token'];
  //       final message = responseData['message'];
  //
  //       await _storageService.write(
  //         key: 'access_token',
  //         value: token,
  //       );
  //
  //       final fcmToken = await NotificationServices().getDeviceToken();
  //       print('fcmToken: $fcmToken');
  //
  //       await _apiClient.post(
  //         ApiUrls.fcmUrl,
  //         data: {'fcmToken': fcmToken},
  //       );
  //
  //       return (true, message.toString());
  //     } else {
  //       // Handle the error based on status code
  //       final responseData = jsonDecode(response.body) as Map<String, dynamic>;
  //       return (false, responseData['message'].toString());
  //     }
  //   } catch (e) {
  //     isLoading(false);
  //     return (false, 'Something went wrong');
  //   }
  // }



Future<void> forgotpass() async{
    isLoading.value = true;
    final response = await authService.forgotPassword(
      {
        'email': emailController.text,
      }
    );
    isLoading.value = false;
    update();
    if(response != null){
     showSnackbar("Email sent successfully");
    }
  }

  Future<void> changePassword() async {
    isLoading.value = true;

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString('token');

    if (token != null) {
      final response = await authService.changePassword(
        {
          'oldPassword': currentpassController.text,
          'newPassword': newpassController.text,
          'confirmPassword': confirmpassController.text,
        },
        token: token, // Pass the token here
      );
    print("tokemn ,$token");
      isLoading.value = false;
      update();

      if (response != null) {

        Get.snackbar('Success', 'Password changed successfully');
      } else {

        Get.snackbar('Error', 'Failed to change password');
      }
    } else {
      isLoading.value = false;
      update();
      Get.snackbar('Error', 'Token not found. Please login again.');
    }
  }


}
