import '/backend/api_requests/api_calls.dart';
import '/components/permission_list_container1_widget.dart';
import '/components/permission_list_container2_widget.dart';
import '/components/permission_list_container3_widget.dart';
import '/components/permission_list_container_widget.dart';
import '/flutterlib/flutter_drop_down.dart';
import '/flutterlib/flutter_theme.dart';
import '/flutterlib/flutter_util.dart';
import '/flutterlib/flutter_widgets.dart';
import '/flutterlib/form_field_controller.dart';
import '/flutterlib/custom_functions.dart' as functions;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'permission_list_view_model.dart';
export 'permission_list_view_model.dart';

class PermissionListViewWidget extends StatefulWidget {
  const PermissionListViewWidget({
    Key? key,
    this.parameter1,
  }) : super(key: key);

  final List<int>? parameter1;

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

class _PermissionListViewWidgetState extends State<PermissionListViewWidget> {
  late PermissionListViewModel _model;

  @override
  void setState(VoidCallback callback) {
    super.setState(callback);
    _model.onUpdate();
  }

  @override
  void initState() {
    super.initState();
    _model = createModel(context, () => PermissionListViewModel());

    // On component load action.
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      setState(() {
        _model.getPermissionsLIst = [];
        _model.getPermissionsLIst1 = [];
        _model.getPermissionsList2 = [];
        _model.getPermissionsList3 = [];
      });
      setState(() => _model.apiRequestCompleter = null);
      await _model.waitForApiRequestCompleted();
      _model.apiResults0e = await NumstationGroup.getPermissionOfRoleCall.call(
        token: FFAppState().token,
        roleId: '7',
      );
      if ((_model.apiResults0e?.succeeded ?? true)) {
        _model.updatePage(() {
          _model.getPermissionsLIst = NumstationGroup.getPermissionOfRoleCall
              .getPermissionsID(
                (_model.apiResults0e?.jsonBody ?? ''),
              )!
              .toList()
              .cast<int>();
        });
      } else {
        await showDialog(
          context: context,
          builder: (alertDialogContext) {
            return AlertDialog(
              content: Text('Failed!'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(alertDialogContext),
                  child: Text('Ok'),
                ),
              ],
            );
          },
        );
      }

      _model.apiResults0a = await NumstationGroup.getPermissionOfRoleCall.call(
        token: FFAppState().token,
        roleId: '8',
      );
      if ((_model.apiResults0a?.succeeded ?? true)) {
        _model.updatePage(() {
          _model.getPermissionsLIst1 = NumstationGroup.getPermissionOfRoleCall
              .getPermissionsID(
                (_model.apiResults0a?.jsonBody ?? ''),
              )!
              .toList()
              .cast<int>();
        });
      } else {
        await showDialog(
          context: context,
          builder: (alertDialogContext) {
            return AlertDialog(
              content: Text('Failed!'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(alertDialogContext),
                  child: Text('Ok'),
                ),
              ],
            );
          },
        );
      }

      _model.apiResults0c = await NumstationGroup.getPermissionOfRoleCall.call(
        token: FFAppState().token,
        roleId: '9',
      );
      if ((_model.apiResults0c?.succeeded ?? true)) {
        _model.updatePage(() {
          _model.getPermissionsList2 = NumstationGroup.getPermissionOfRoleCall
              .getPermissionsID(
                (_model.apiResults0c?.jsonBody ?? ''),
              )!
              .toList()
              .cast<int>();
        });
      } else {
        await showDialog(
          context: context,
          builder: (alertDialogContext) {
            return AlertDialog(
              content: Text('Failed!'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(alertDialogContext),
                  child: Text('Ok'),
                ),
              ],
            );
          },
        );
      }

      _model.apiResults0d = await NumstationGroup.getPermissionOfRoleCall.call(
        token: FFAppState().token,
        roleId: '10',
      );
      if ((_model.apiResults0d?.succeeded ?? true)) {
        _model.updatePage(() {
          _model.getPermissionsList3 = NumstationGroup.getPermissionOfRoleCall
              .getPermissionsID(
                (_model.apiResults0d?.jsonBody ?? ''),
              )!
              .toList()
              .cast<int>();
        });
      } else {
        await showDialog(
          context: context,
          builder: (alertDialogContext) {
            return AlertDialog(
              content: Text('Failed!'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(alertDialogContext),
                  child: Text('Ok'),
                ),
              ],
            );
          },
        );
      }
    });
  }

  @override
  void dispose() {
    _model.maybeDispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    context.watch<FFAppState>();

    return Padding(
      padding: EdgeInsetsDirectional.fromSTEB(10.0, 0.0, 10.0, 0.0),
      child: ListView(
        padding: EdgeInsets.fromLTRB(
          0,
          5.0,
          0,
          10.0,
        ),
        scrollDirection: Axis.vertical,
        children: [
          Align(
            alignment: AlignmentDirectional(0.0, -1.0),
            child: Container(
              decoration: BoxDecoration(),
              child: Padding(
                padding: EdgeInsetsDirectional.fromSTEB(0.0, 10.0, 0.0, 10.0),
                child: FutureBuilder<ApiCallResponse>(
                  future: (_model.apiRequestCompleter ??=
                          Completer<ApiCallResponse>()
                            ..complete(NumstationGroup.roleListCall.call(
                              token: FFAppState().token,
                            )))
                      .future,
                  builder: (context, snapshot) {
                    // Customize what your widget looks like when it's loading.
                    if (!snapshot.hasData) {
                      return Center(
                        child: SizedBox(
                          width: 50.0,
                          height: 50.0,
                          child: CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation<Color>(
                              FlutterTheme.of(context).info,
                            ),
                          ),
                        ),
                      );
                    }
                    final role1223RoleListResponse = snapshot.data!;
                    return FlutterDropDown<String>(
                      controller: _model.role1223ValueController ??=
                          FormFieldController<String>(null),
                      options: List<String>.from((getJsonField(
                        role1223RoleListResponse.jsonBody,
                        r'''$.roles..id''',
                        true,
                      ) as List)
                          .map<String>((s) => s.toString())
                          .toList()!),
                      optionLabels: functions.addAccessRightPrefix(getJsonField(
                        role1223RoleListResponse.jsonBody,
                        r'''$.roles..display_name''',
                        true,
                      )!),
                      onChanged: (val) async {
                        setState(() => _model.role1223Value = val);
                        _model.updatePage(() {
                          _model.roleID = _model.role1223Value!;
                        });
                        FFAppState().update(() {
                          FFAppState().deleteAddPermissionsID();
                          FFAppState().addPermissionsID = [];

                          FFAppState().deleteRemovePermissionsID();
                          FFAppState().removePermissionsID = [];
                        });
                      },
                      width: 360.0,
                      height: 43.0,
                      textStyle:
                          FlutterTheme.of(context).bodyMedium.override(
                                fontFamily: 'Readex Pro',
                                fontSize: 20.0,
                                fontWeight: FontWeight.w500,
                                lineHeight: 1.2,
                              ),
                      hintText: FFLocalizations.of(context).getText(
                        'wm69kw1i' /* Access right : */,
                      ),
                      icon: Icon(
                        Icons.keyboard_arrow_down_rounded,
                        color: FlutterTheme.of(context).secondaryText,
                        size: 24.0,
                      ),
                      fillColor:
                          FlutterTheme.of(context).secondaryBackground,
                      elevation: 2.0,
                      borderColor: FlutterTheme.of(context).alternate,
                      borderWidth: 2.0,
                      borderRadius: 8.0,
                      margin:
                          EdgeInsetsDirectional.fromSTEB(10.0, 4.0, 16.0, 4.0),
                      hidesUnderline: true,
                      isSearchable: false,
                      isMultiSelect: false,
                    );
                  },
                ),
              ),
            ),
          ),
          if (_model.roleID == '7')
            wrapWithModel(
              model: _model.permissionListContainerModel,
              updateCallback: () => setState(() {}),
              updateOnChange: true,
              child: PermissionListContainerWidget(
                roleID: _model.role1223Value,
                getPermissionsList: _model.getPermissionsLIst,
              ),
            ),
          if (_model.roleID == '8')
            wrapWithModel(
              model: _model.permissionListContainer1Model,
              updateCallback: () => setState(() {}),
              child: PermissionListContainer1Widget(
                getPermissionsList: _model.getPermissionsLIst1,
              ),
            ),
          if (_model.roleID == '9')
            wrapWithModel(
              model: _model.permissionListContainer2Model,
              updateCallback: () => setState(() {}),
              child: PermissionListContainer2Widget(
                getPermissionsList: _model.getPermissionsList2,
              ),
            ),
          if (_model.roleID == '10')
            wrapWithModel(
              model: _model.permissionListContainer3Model,
              updateCallback: () => setState(() {}),
              child: PermissionListContainer3Widget(
                getPermissionsList: _model.getPermissionsList3,
              ),
            ),
          Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              FFButtonWidget(
                onPressed: () async {
                  while (_model.loopCounter! <
                      FFAppState().addPermissionsID.length) {
                    _model.apiResulttvj =
                        await NumstationGroup.addPermissionToRoleCall.call(
                      token: FFAppState().token,
                      roleId: _model.roleID,
                      permissionId:
                          FFAppState().addPermissionsID[_model.loopCounter!],
                    );
                    setState(() {
                      _model.loopCounter = _model.loopCounter! + 1;
                    });
                  }
                  _model.updatePage(() {
                    _model.loopCounter = 0;
                    _model.filteredRemovePermissions = functions
                        .filteredRemovePermissions(
                            FFAppState().addPermissionsID.toList(),
                            FFAppState().removePermissionsID.toList())
                        .toList()
                        .cast<String>();
                  });
                  while (_model.loopCounter! <
                      _model.filteredRemovePermissions.length) {
                    _model.apiResulttvq =
                        await NumstationGroup.removePermissionToRoleCall.call(
                      token: FFAppState().token,
                      roleId: _model.roleID,
                      permissionId:
                          _model.filteredRemovePermissions[_model.loopCounter!],
                    );
                    setState(() {
                      _model.loopCounter = _model.loopCounter! + 1;
                    });
                  }
                  _model.updatePage(() {
                    _model.loopCounter = 0;
                  });
                  setState(() {
                    FFAppState().deleteAddPermissionsID();
                    FFAppState().addPermissionsID = [];

                    FFAppState().deleteRemovePermissionsID();
                    FFAppState().removePermissionsID = [];
                  });

                  context.pushNamed('user');

                  setState(() {});
                },
                text: FFLocalizations.of(context).getText(
                  'hke183b6' /* Save */,
                ),
                options: FFButtonOptions(
                  width: 159.0,
                  height: 50.0,
                  padding: EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0),
                  iconPadding:
                      EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0),
                  color: Color(0xFF009B9A),
                  textStyle: FlutterTheme.of(context).titleSmall.override(
                        fontFamily: 'Readex Pro',
                        color: Colors.white,
                        fontSize: 20.0,
                      ),
                  elevation: 3.0,
                  borderSide: BorderSide(
                    color: Colors.transparent,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.circular(40.0),
                ),
              ),
              FFButtonWidget(
                onPressed: () async {
                  context.pushNamed('user');
                },
                text: FFLocalizations.of(context).getText(
                  '9enzv173' /* Reset */,
                ),
                options: FFButtonOptions(
                  width: 159.0,
                  height: 50.0,
                  padding: EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0),
                  iconPadding:
                      EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0),
                  color: Color(0xFF9B0025),
                  textStyle: FlutterTheme.of(context).titleSmall.override(
                        fontFamily: 'Readex Pro',
                        color: Colors.white,
                        fontSize: 20.0,
                      ),
                  elevation: 3.0,
                  borderSide: BorderSide(
                    color: Colors.transparent,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.circular(40.0),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
