import 'package:hmg_patient_app/core/service/medical/labs_service.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.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/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class WorkplaceUpdatePage extends StatefulWidget {
  final int requestNumber;
  final String setupID;
  final int projectID;

  WorkplaceUpdatePage({required this.requestNumber, required this.setupID, required this.projectID});

  @override
  _WorkplaceUpdatePageState createState() => _WorkplaceUpdatePageState();
}

class _WorkplaceUpdatePageState extends State<WorkplaceUpdatePage> {
  TextEditingController workplaceName = new TextEditingController();

  TextEditingController workplaceNameAr = new TextEditingController();
  TextEditingController occupationNameEn = new TextEditingController();
  TextEditingController occupationNameAr = new TextEditingController();
  bool? _isButtonDisabled;
  ProjectViewModel? projectViewModel;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).sickLeaves,
      isShowAppBar: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGrey2Color,
      body: Container(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      mHeight(12),
                      SvgPicture.asset("assets/images/new/workplace-icon.svg", width: 40.0, fit: BoxFit.fill),
                      mHeight(12),
                      Text(
                        TranslationBase.of(context).enterWorkplaceName,
                        textAlign: TextAlign.start,
                        style: TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.black,
                          letterSpacing: -0.64,
                        ),
                      ),
                      mHeight(8),
                      // inputWidget(TranslationBase.of(context).workplaceName, "", workplaceName),
                      inputWidget(TranslationBase.of(context).workplaceName, "", workplaceName, FilteringTextInputFormatter.allow(RegExp("[a-zA-Z ]"))),
                      mHeight(8),
                      inputWidget(TranslationBase.of(context).workplaceNameAr, "", workplaceNameAr, FilteringTextInputFormatter.allow(RegExp("[ء-ي ]"))),
                      mHeight(8),
                      inputWidget(TranslationBase.of(context).occupationNameEn, "", occupationNameEn, FilteringTextInputFormatter.allow(RegExp("[a-zA-Z ]"))),
                      mHeight(8),
                      inputWidget(TranslationBase.of(context).occupationNameAr, "", occupationNameAr, FilteringTextInputFormatter.allow(RegExp("[ء-ي ]"))),
                    ],
                  ),
                ),
              ),
            ),
            Card(
              margin: EdgeInsets.zero,
              elevation: 0,
              child: Container(
                padding: EdgeInsets.all(12),
                child: FractionallySizedBox(
                  widthFactor: 1,
                  child: MaterialButton(
                    height: 50,
                    elevation: 0,
                    color: CustomColors.accentColor,
                    disabledColor: Colors.grey.withOpacity(0.25),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    child: Text(
                      TranslationBase.of(context).submit,
                      style: TextStyle(
                        fontSize: 16.0,
                        letterSpacing: -0.64,
                        color: Colors.white,
                      ),
                    ),
                    onPressed: () {
                      // if (_isButtonDisabled == false)
                      if (workplaceNameAr.text.isNotEmpty && occupationNameAr.text.isNotEmpty)
                        // AppToast.showSuccessToast(message: "API Called");
                        updateWorkplaceNameDialog();
                      else
                        AppToast.showErrorToast(message: TranslationBase.of(context).enterDetailBelow);
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, TextInputFormatter inputFormatter, {String? prefix, bool isEnable = true, bool hasSelection = false}) {
  // Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String? prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.name,
                    controller: _controller,
                    inputFormatters: [
                      // projectViewModel!.isArabic ? FilteringTextInputFormatter.allow(RegExp("[ء-ي ]")) : FilteringTextInputFormatter.allow(RegExp("[a-zA-Z ]")),
                      inputFormatter
                    ],
                    onChanged: (value) => {_onPassportTextChanged(value)},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }

  _onPassportTextChanged(content) {
    if (content.length >= 1) {
      setState(() {
        _isButtonDisabled = false;
      });
    } else {
      setState(() {
        _isButtonDisabled = true;
      });
    }
  }

  updateWorkplaceNameDialog() {
    var messageEn = "The workplace name you entered is: " + workplaceNameAr.text + ". Please confirm!";
    var messageAr = "اسم مكان العمل الذي أدخلته هو: " + workplaceNameAr.text + ". يرجى تأكيد!";
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: projectViewModel!.isArabic ? messageAr : messageEn,
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () {
          Navigator.of(context).pop();
          updateWorkplaceName();
        },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  void updateWorkplaceName() {
    LabsService service = new LabsService();
    GifLoaderDialogUtils.showMyDialog(context);

    service.updateWorkplaceName(workplaceName.text, workplaceNameAr.text, occupationNameEn.text, occupationNameAr.text, widget.requestNumber, widget.setupID, widget.projectID).then((res) {
    // service
    //     .updateWorkplaceName(projectViewModel!.isArabic ? "-" : workplaceName.text, projectViewModel!.isArabic ? workplaceName.text : "-", widget.requestNumber, widget.setupID, widget.projectID)
    //     .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      Navigator.of(context).pop(true);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
