import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/components/molecular_components/message_opt_modal/opt_modal_model.dart';
import 'package:hub/flutter_flow/flutter_flow_model.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/flutter_flow/nav/nav.dart';

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

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

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

class _OptModalWidgetState extends State<OptModalWidget> {
  late OptModalModel _model;

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

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

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

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

    _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) {
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(0.0, 10.0, 0.0, 0.0),
              child: Text(
                FFLocalizations.of(context).getText('l7tw8b92'),
                textAlign: TextAlign.left, // Adiciona esta linha para alinhar o texto à esquerda
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      letterSpacing: 0.0,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(FlutterFlowTheme.of(context).bodyMediumFamily),
                      color: FlutterFlowTheme.of(context).primaryText,
                    ),
              ),
            ),
          ],
        ),
        ListView.builder(
          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,
                      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: 10,
                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) {
    return SafeArea(
      child: Align(
        alignment: const AlignmentDirectional(1.0, -1.0),
        child: Padding(
          padding: const EdgeInsetsDirectional.fromSTEB(0.0, 50.0, 50.0, 0.0),
          child: Container(
            width: 300.0,
            height: 450.0,
            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: 16.0,
                                letterSpacing: 0.0,
                                useGoogleFonts:
                                    GoogleFonts.asMap().containsKey(FlutterFlowTheme.of(context).headlineMediumFamily),
                              ),
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsetsDirectional.fromSTEB(8.0, 0.0, 8.0, 0.0),
                    child: TextFormField(
                      controller: _model.textController,
                      focusNode: _model.textFieldFocusNode,
                      autofocus: false,
                      obscureText: false,
                      decoration: InputDecoration(
                        isDense: true,
                        labelText: FFLocalizations.of(context).getText(
                          '0enrtljz' /* Pesquise aqui..... */,
                        ),
                        labelStyle: FlutterFlowTheme.of(context).labelMedium.override(
                              fontFamily: FlutterFlowTheme.of(context).labelMediumFamily,
                              color: FlutterFlowTheme.of(context).primaryText,
                              letterSpacing: 0.0,
                              useGoogleFonts:
                                  GoogleFonts.asMap().containsKey(FlutterFlowTheme.of(context).labelMediumFamily),
                            ),
                        hintStyle: FlutterFlowTheme.of(context).labelMedium.override(
                              fontFamily: FlutterFlowTheme.of(context).labelMediumFamily,
                              color: FlutterFlowTheme.of(context).primaryText,
                              letterSpacing: 0.0,
                              useGoogleFonts:
                                  GoogleFonts.asMap().containsKey(FlutterFlowTheme.of(context).labelMediumFamily),
                            ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: FlutterFlowTheme.of(context).alternate,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: FlutterFlowTheme.of(context).primary,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        errorBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: FlutterFlowTheme.of(context).error,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        focusedErrorBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: FlutterFlowTheme.of(context).error,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        filled: true,
                        fillColor: FlutterFlowTheme.of(context).alternate,
                        suffixIcon: const Icon(
                          Icons.search_outlined,
                        ),
                      ),
                      style: FlutterFlowTheme.of(context).bodyMedium.override(
                            fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                            letterSpacing: 0.0,
                            useGoogleFonts:
                                GoogleFonts.asMap().containsKey(FlutterFlowTheme.of(context).bodyMediumFamily),
                          ),
                      validator: _model.textControllerValidator.asValidator(context),
                    ),
                  ),
                  SingleChildScrollView(
                    child: Container(
                      padding: const EdgeInsets.all(20),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          _buildCheckboxListTile('personType', personTypeOptions),
                          _buildCheckboxListTile('accessType', accessTypeOptions),
                        ],
                      ),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: _applyFilter,
                    style: ElevatedButton.styleFrom(
                      foregroundColor: FlutterFlowTheme.of(context).info,
                      backgroundColor: FlutterFlowTheme.of(context).primary,
                    ),
                    child: Text(FFLocalizations.of(context).getText('88kshkph')),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
