import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../core/config/server_response.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/fields_utils.dart';
import '../../../core/utils/logs_utils.dart';
import '../../../custom_widgets/Fields/field_validations.dart';
import '../../../custom_widgets/Fields/input_field.dart';
import '../../../custom_widgets/custom_dialog.dart';
import '../../../custom_widgets/custom_dropdown.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/AddNewAccountRequestModel.dart';
import '../../../models/product_model.dart';
import '../../../routes/app_pages.dart';
import '../../dashboard/controllers/dashboard_screen_controller.dart';

class AddNewAccountController extends GetxController {
  BuildContext context = Get.context as BuildContext;

  late InputField currencyCodesField;
  late InputField nameAddressField;

  DropDown dropDownValue = DropDown.empty();

  List<ProductDepositModel> currencyList = [];

  List<DropDown> currencyListDropDown = [];

  final AppRepositories repository = Get.find<AppRepositories>();

  void updateCurrency(DropDown? item) {
    dropDownValue = item!;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    getCurrencyList();
  }

  /// Validate Function of contorller
  bool validate() {
    bool isValid = FieldValidation.validateAll([
      nameAddressField,
      currencyCodesField,
    ]);
    return isValid;
  }

  /// Get Currency List Function
  getCurrencyList() async {
    try {
      var productResponse = await repository.getCurrencyList();
      //
      if (productResponse.isError) {
        Toasty.error(productResponse.errorMsg);
        return;
      }

      currencyList = ProductDepositModel.productListFromJson(
        productResponse.response,
      );

      currencyListDropDown = currencyList
          .map((e) => DropDown(e.dmpProdcode, e.dmpProddesc, e))
          .toList();

      dropDownValue = currencyListDropDown.first;

      dp("DmpProductCode", currencyListDropDown);

      update();
    } catch (e, s) {
      dp("Error in get product $e", s);
      Toasty.error("Something went wrong, please try again");
    }
  }

  /// New Create Account Request Function
  void validateAndSendRequest() async {
    hideKeyBoard();
    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }

    AddNewAccountRequestModel request = AddNewAccountRequestModel(
      title: nameAddressField.getCustomText(),
      porOrgacode: SessionCache.instance.userInfo.porOrgacode,
      channelCode: SessionCache.instance.userInfo.channelCode,
      dmpProdcode: dropDownValue.id,
      email: SessionCache.instance.userInfo.cmpUserId,
    );

    ServerResponse response = await repository.addNewAccount(request);

    if (response.errorCode == "ERR_ACC_0012") {
      Toasty.error("Account for the product already exists");
      return;
    }

    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    CustomDialog.showSuccessDialog(
      description:
          "Thank you so much, Your new account has been created successfully",
      onTapPositive: () {
        transitionUpdate.value++;

        Navigator.of(context, rootNavigator: true).pop();

        Get.offAllNamed(Routes.DASHBOARD_SCREEN);
      },
    );

    clearText();
  }

  /// Clear Controller Function
  clearText() {
    nameAddressField.clear();
    currencyCodesField.clear();
    update();
  }
}
