import 'package:hmg_patient_app/core/model/insurance/insuranceManualUpdateRequest.dart';
import 'package:hmg_patient_app/core/service/insurance_service.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/insurance/getInsuranceCompaniesModel.dart';
import 'package:hmg_patient_app/models/insurance/insuranceCompaniesSchemeModel.dart';
import 'package:hmg_patient_app/pages/medical/balance/new_text_Field.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/dialogs/radio_selection_dialog.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class UpdateInsuranceManually extends StatefulWidget {
  String patientIdentificationNo;
  String patientMobileNumber;
  int patientID;

  UpdateInsuranceManually({required this.patientIdentificationNo, required this.patientMobileNumber, required this.patientID});

  @override
  State<UpdateInsuranceManually> createState() => _UpdateInsuranceManuallyState();
}

class _UpdateInsuranceManuallyState extends State<UpdateInsuranceManually> {
  TextEditingController _nationalIDTextController = TextEditingController();
  TextEditingController _cardHolderNameTextController = TextEditingController();
  TextEditingController _membershipNoTextController = TextEditingController();
  TextEditingController _policyNoTextController = TextEditingController();
  late ProjectViewModel projectViewModel;

  InsuranceCardService _insuranceCardService = locator<InsuranceCardService>();

  List<InsuranceCompaniesGetModel> insuranceCompaniesList = [];
  List<InsuranceCompaniesSchemeModel> insuranceCompaniesSchemesList = [];

  int _selectedInsuranceCompanyIndex = -1;
  int _selectedInsuranceCompanySchemeIndex = -1;

  late InsuranceCompaniesGetModel selectedInsuranceCompanyObj;
  late InsuranceCompaniesSchemeModel selectedInsuranceCompaniesSchemesObj;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInsuranceCompanies();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    _nationalIDTextController.text = widget.patientIdentificationNo;
    return AppScaffold(
      isShowAppBar: true,
      isShowDecPage: false,
      appBarTitle: TranslationBase.of(context).updateInsurCards,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(21),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                TranslationBase.of(context).enterInsuranceDetails,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 16,
                  letterSpacing: -0.48,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 12),
              InkWell(
                onTap: () {
                  confirmSelectInsuranceCompanyDialog();
                },
                child: Container(
                  padding: EdgeInsets.all(8),
                  width: double.infinity,
                  height: 65,
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Colors.white),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        selectedInsuranceCompanyObj != null ? selectedInsuranceCompanyObj.companyName! : TranslationBase.of(context).insuranceCompany,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.46,
                        ),
                      ),
                      Icon(Icons.arrow_drop_down)
                    ],
                  ),
                ),
              ),
              SizedBox(height: 12),
              NewTextFields(
                hintText: TranslationBase.of(context).nationalIdNumber,
                controller: _nationalIDTextController,
                readOnly: true,
              ),
              SizedBox(height: 12),
              NewTextFields(
                hintText: TranslationBase.of(context).cardHolderName,
                controller: _cardHolderNameTextController,
                readOnly: false,
              ),
              SizedBox(height: 12),
              NewTextFields(
                hintText: TranslationBase.of(context).membershipNo,
                controller: _membershipNoTextController,
                readOnly: false,
              ),
              SizedBox(height: 12),
              NewTextFields(
                hintText: TranslationBase.of(context).insurancePolicyNo,
                controller: _policyNoTextController,
                readOnly: false,
              ),
              SizedBox(height: 12),
              InkWell(
                onTap: () {
                  confirmSelectInsuranceCompanySchemeDialog();
                },
                child: Container(
                  padding: EdgeInsets.all(8),
                  width: double.infinity,
                  height: 65,
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Colors.white),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        selectedInsuranceCompaniesSchemesObj != null ? selectedInsuranceCompaniesSchemesObj.subCategoryDesc! : TranslationBase.of(context).insuranceClassName,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.46,
                        ),
                      ),
                      Icon(Icons.arrow_drop_down)
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        padding: EdgeInsets.all(18),
        child: DefaultButton(
          TranslationBase.of(context).submit,
          () {
            if (isFormValid())
              submitManualInsuranceUpdateRequest();
            else
              AppToast.showErrorToast(message: TranslationBase.of(context).enterInsuranceDetails);
          },
          disabledColor: Colors.grey,
        ),
      ),
    );
  }

  bool isFormValid() {
    if (selectedInsuranceCompanyObj != null &&
        _cardHolderNameTextController.text.isNotEmpty &&
        _membershipNoTextController.text.isNotEmpty &&
        _policyNoTextController.text.isNotEmpty &&
        selectedInsuranceCompaniesSchemesObj != null) {
      return true;
    } else {
      return false;
    }
  }

  void confirmSelectInsuranceCompanyDialog() {
    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < insuranceCompaniesList.length; i++) RadioSelectionDialogModel(insuranceCompaniesList[i].companyName!, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        selectedIndex: _selectedInsuranceCompanyIndex,
        isScrollable: true,
        isShowSearch: true,
        onValueSelected: (index) {
          _selectedInsuranceCompanyIndex = index;
          selectedInsuranceCompanyObj = insuranceCompaniesList[index];
          setState(() {});
          getInsuranceScheme();
        },
      ),
    );
  }

  void confirmSelectInsuranceCompanySchemeDialog() {
    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < insuranceCompaniesSchemesList.length; i++) RadioSelectionDialogModel(insuranceCompaniesSchemesList[i].subCategoryDesc!, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        selectedIndex: _selectedInsuranceCompanySchemeIndex,
        isScrollable: true,
        onValueSelected: (index) {
          _selectedInsuranceCompanySchemeIndex = index;
          selectedInsuranceCompaniesSchemesObj = insuranceCompaniesSchemesList[index];
          setState(() {});
        },
      ),
    );
  }

  void getInsuranceCompanies() {
    GifLoaderDialogUtils.showMyDialog(context);
    _insuranceCardService.getInsuranceCompanies().then((value) {
      value.forEach((result) {
        insuranceCompaniesList.add(InsuranceCompaniesGetModel.fromJson(result));
      });
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  void submitManualInsuranceUpdateRequest() {
    GifLoaderDialogUtils.showMyDialog(context);

    InsuranceManualUpdateRequest insuranceManualUpdateRequest = new InsuranceManualUpdateRequest();

    insuranceManualUpdateRequest.projectID = selectedInsuranceCompanyObj.projectID;
    insuranceManualUpdateRequest.requestType = 2;
    insuranceManualUpdateRequest.mobileNo = widget.patientMobileNumber;
    insuranceManualUpdateRequest.cardHolderName = _cardHolderNameTextController.text;
    insuranceManualUpdateRequest.insuranceCompanyName = selectedInsuranceCompanyObj.companyName;
    insuranceManualUpdateRequest.memberShipNo = _membershipNoTextController.text;
    insuranceManualUpdateRequest.policyNo = _policyNoTextController.text;
    insuranceManualUpdateRequest.patientIdentificationID = widget.patientIdentificationNo;
    insuranceManualUpdateRequest.schemeClass = selectedInsuranceCompaniesSchemesObj.subCategoryDesc;
    insuranceManualUpdateRequest.setupID = selectedInsuranceCompanyObj.setupID;
    insuranceManualUpdateRequest.patientID = widget.patientID;

    _insuranceCardService.submitManualInsuranceUpdateRequest(insuranceManualUpdateRequest).then((value) {
      print(value);
      AppToast.showSuccessToast(message: TranslationBase.of(context).insuranceRequestSubmit);
      Navigator.pop(context);
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err.toString());
    });
  }

  void getInsuranceScheme() {
    GifLoaderDialogUtils.showMyDialog(context);
    _insuranceCardService.getInsuranceSchemes(selectedInsuranceCompanyObj.projectID!, selectedInsuranceCompanyObj.companyID!).then((value) {
      value.forEach((result) {
        insuranceCompaniesSchemesList.add(InsuranceCompaniesSchemeModel.fromJson(result));
      });
      GifLoaderDialogUtils.hideDialog(context);
    });
  }
}
