import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/form_field_controller.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/utils/limited_text_size.dart';

class AccessFilterModel extends FlutterFlowModel<AccessFilter> {
  ///  State fields for stateful widgets in this component.

  // State field(s) for TextField widget.
  FocusNode? textFieldFocusNode;
  TextEditingController? textController;
  String? Function(BuildContext, String?)? textControllerValidator;
  // State field(s) for Checkbox widget.
  bool? checkboxValue1;
  // State field(s) for Checkbox widget.
  bool? checkboxValue2;
  // State field(s) for CheckboxGroup widget.
  FormFieldController<List<String>>? checkboxGroupValueController;
  List<String>? get checkboxGroupValues => checkboxGroupValueController?.value;
  set checkboxGroupValues(List<String>? v) =>
      checkboxGroupValueController?.value = v;

  @override
  void initState(BuildContext context) {}

  @override
  void dispose() {
    textFieldFocusNode?.dispose();
    textController?.dispose();
  }
}

class AccessFilter extends StatefulWidget {
  final String defaultPersonType;
  final String defaultAccessType;

  const AccessFilter({
    super.key,
    this.defaultPersonType = '.*',
    this.defaultAccessType = '.*',
  });

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

class _AccessFilterState extends State<AccessFilter> {
  late AccessFilterModel _model;

  late Map<String, dynamic> selected;
  final List<Map<String, String>> personTypeOptions = [
    {'title': 'zok7lu4w', 'value': 'E'},
    {'title': 'oonqk812', 'value': 'O'},
  ];

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

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

    _model = createModel(context, () => AccessFilterModel());

    _model.textController ??= TextEditingController();
    _model.textFieldFocusNode ??= FocusNode();

    selected = {
      'personType': widget.defaultPersonType == '.*'
          ? ['E', 'O']
          : [widget.defaultPersonType],
      'accessType': widget.defaultAccessType == '.*'
          ? ['0', '1']
          : [widget.defaultAccessType],
      'search': '.*',
    };
  }

  void _applyFilter() {
    Map<String, String> filterResult = {
      'personType': '',
      'accessType': '',
      'search': _model.textController?.text == ''
          ? '.*'
          : _model.textController!.text.toLowerCase(),
    };

    if (selected['personType']!.isEmpty) {
      filterResult['personType'] = '.*';
    } else if (selected['personType']!.length > 1) {
      filterResult['personType'] = '.*';
    } else {
      filterResult['personType'] = selected['personType']!.first;
    }

    if (selected['accessType']!.isEmpty) {
      filterResult['accessType'] = '.*';
    } else if (selected['accessType']!.length > 1) {
      filterResult['accessType'] = '.*';
    } else {
      filterResult['accessType'] = selected['accessType']!.first;
    }

    // Navigator.pop(context, filterResult);
    context.pop(filterResult);
  }

  Widget _buildCheckboxListTile(
      String key, List<Map<String, String>> options, double fontsize) {
    double limitedInputFontSize = LimitedFontSizeUtil.getInputFontSize(context);
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(0.0, 3.0, 0.0, 0.0),
              child: Text(
                FFLocalizations.of(context).getText('l7tw8b92'),
                textAlign: TextAlign.left,
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      fontSize: limitedInputFontSize,
                      letterSpacing: 0.0,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(
                          FlutterFlowTheme.of(context).bodyMediumFamily),
                      color: FlutterFlowTheme.of(context).primaryText,
                    ),
              ),
            ),
          ],
        ),
        ListView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: options.length,
          itemBuilder: (context, index) {
            final option = options[index];
            return CheckboxListTile(
              title: Text(
                FFLocalizations.of(context).getText(option['title']!),
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      letterSpacing: 0.0,
                      fontSize: limitedInputFontSize,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(
                          FlutterFlowTheme.of(context).bodyMediumFamily),
                      color: FlutterFlowTheme.of(context).primaryText,
                    ),
              ),
              dense: true,
              value: selected[key]!.contains(option['value']),
              onChanged: (bool? value) {
                setState(() {
                  if (value == true) {
                    if (!selected[key]!.contains(option['value'])) {
                      selected[key]!.add(option['value']);
                    }
                  } else {
                    selected[key]!.remove(option['value']);
                  }
                });
              },
              activeColor: FlutterFlowTheme.of(context).primary,
              checkColor: FlutterFlowTheme.of(context).info,
              checkboxShape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(100),
              ),
              enableFeedback: true,
              side: BorderSide(
                width: 5,
                color: FlutterFlowTheme.of(context).secondaryText,
              ),
              controlAffinity:
                  ListTileControlAffinity.leading, // Adiciona esta linha
            );
          },
        ),
      ],
    );
  }

  void _updateSelection(String? value, String key) {
    setState(() {
      if (value == '.') {
        selected[key] = [];
      } else if (value != null) {
        if (selected[key]!.contains(value)) {
          selected[key]!.remove(value);
        } else {
          selected[key]!.add(value);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;

    return Center(
      child: Container(
        width: screenWidth - (screenWidth * 0.35),
        height: 250,
        decoration: BoxDecoration(
          color: FlutterFlowTheme.of(context).primaryBackground,
          borderRadius: BorderRadius.circular(24.0),
        ),
        child: Padding(
          padding: const EdgeInsets.all(4.0),
          child: Column(
            children: [
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsetsDirectional.fromSTEB(
                        10.0, 10.0, 0.0, 10.0),
                    child: Text(
                      FFLocalizations.of(context)
                          .getText('yfj9pd6k'), // Filtros
                      style: FlutterFlowTheme.of(context)
                          .headlineMedium
                          .override(
                            fontFamily: FlutterFlowTheme.of(context)
                                .headlineMediumFamily,
                            color: FlutterFlowTheme.of(context).primaryText,
                            fontSize:
                                LimitedFontSizeUtil.getHeaderFontSize(context),
                            letterSpacing: 0.0,
                            fontWeight: FontWeight.bold,
                            useGoogleFonts: GoogleFonts.asMap().containsKey(
                                FlutterFlowTheme.of(context)
                                    .headlineMediumFamily),
                          ),
                    ),
                  ),
                ],
              ),
              Expanded(
                child: SingleChildScrollView(
                  child: Container(
                    padding: const EdgeInsets.all(10),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        _buildCheckboxListTile(
                            'personType', personTypeOptions, 14),
                      ],
                    ),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: _applyFilter,
                style: ElevatedButton.styleFrom(
                  foregroundColor: FlutterFlowTheme.of(context).info,
                  backgroundColor: FlutterFlowTheme.of(context).primary,
                ),
                child: Text(FFLocalizations.of(context).getText('88kshkph'),
                    style: FlutterFlowTheme.of(context).bodyMedium.override(
                          fontFamily:
                              FlutterFlowTheme.of(context).bodyMediumFamily,
                          color: FlutterFlowTheme.of(context).info,
                          fontSize:
                              LimitedFontSizeUtil.getInputFontSize(context),
                          letterSpacing: 0.0,
                          fontWeight: FontWeight.bold,
                          useGoogleFonts: GoogleFonts.asMap().containsKey(
                              FlutterFlowTheme.of(context).bodyMediumFamily),
                        )),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
