import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/components/atomic_components/shared_components_atoms/toast.dart';
import 'package:hub/components/molecular_components/visitor_not_found_component/visitor_not_found_component_widget.dart';
import 'package:hub/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_model.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/flutter_flow/flutter_flow_icon_button.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/flutter_flow_widgets.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/utils/limited_text_size.dart';

class VisitorSearchModalTemplateComponentWidget extends StatefulWidget {
  const VisitorSearchModalTemplateComponentWidget({
    super.key,
    this.getVisitors,
    this.getDocs,
  });

  final Future Function(List<dynamic>? visitorsParam)? getVisitors;
  final Future Function(List<String>? docsParam)? getDocs;

  @override
  State<VisitorSearchModalTemplateComponentWidget> createState() =>
      _VisitorSearchModalTemplateComponentWidgetState();
}

class _VisitorSearchModalTemplateComponentWidgetState
    extends State<VisitorSearchModalTemplateComponentWidget>
    with TickerProviderStateMixin {
  late VisitorSearchModalTemplateComponentModel _model;

  safeSetState(VoidCallback callback) {
    super.setState(callback);
    _model.onUpdate();
  }

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

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

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

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final double limitedInputFontSize =
        LimitedFontSizeUtil.getInputFontSize(context);
    final double limitedHeaderFontSize =
        LimitedFontSizeUtil.getHeaderFontSize(context);
    final double limitedBodyFontSize =
        LimitedFontSizeUtil.getBodyFontSize(context);

    return Padding(
      padding: const EdgeInsetsDirectional.fromSTEB(0.0, 10.0, 0.0, 0.0),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            width: 40,
            height: 5,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(10),
            ),
          ),
          Column(
            children: [],
          ),
          Padding(
            padding:
                const EdgeInsetsDirectional.fromSTEB(16.0, 25.0, 16.0, 0.0),
            child: TextFormField(
              controller: _model.textController,
              focusNode: _model.textFieldFocusNode,
              onFieldSubmitted: (_) async {
                await addVisitor(context);
                safeSetState(() {});
              },
              autofocus: false,
              textInputAction: TextInputAction.done,
              obscureText: false,
              decoration: InputDecoration(
                isDense: true,
                labelText: FFLocalizations.of(context).getVariableText(
                  enText: 'Document of the Visitor',
                  ptText: 'Documento do Visitante',
                ),
                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),
                      fontSize: limitedInputFontSize,
                    ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).accent1, width: 0.5),
                  borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(15.0),
                      bottomRight: Radius.circular(15.0),
                      topLeft: Radius.circular(15.0),
                      topRight: Radius.circular(15.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).primary, width: 0.5),
                  borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(15.0),
                      bottomRight: Radius.circular(15.0),
                      topLeft: Radius.circular(15.0),
                      topRight: Radius.circular(15.0)),
                ),
                errorBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).error, width: 0.5),
                  borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(15.0),
                      bottomRight: Radius.circular(15.0),
                      topLeft: Radius.circular(15.0),
                      topRight: Radius.circular(15.0)),
                ),
                focusedErrorBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).error, width: 0.5),
                  borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(15.0),
                      bottomRight: Radius.circular(15.0),
                      topLeft: Radius.circular(15.0),
                      topRight: Radius.circular(15.0)),
                ),
                filled: true,
                fillColor: FlutterFlowTheme.of(context).primaryBackground,
                prefixIcon: Icon(Icons.search_outlined,
                    color: FlutterFlowTheme.of(context).accent1),
              ),
              style: FlutterFlowTheme.of(context).bodyMedium.override(
                    fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                    letterSpacing: 0.0,
                    useGoogleFonts: GoogleFonts.asMap().containsKey(
                        FlutterFlowTheme.of(context).bodyMediumFamily),
                    fontSize: limitedInputFontSize,
                  ),
              keyboardType: const TextInputType.numberWithOptions(signed: true),
              validator: _model.textControllerValidator.asValidator(context),
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp('[0-9]'))
              ],
            ),
          ),
          if (_model.visitors.isNotEmpty && _model.visitors.isNotEmpty)
            Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsetsDirectional.fromSTEB(
                      16.0, 12.0, 0.0, 0.0),
                  child: Text(
                    FFLocalizations.of(context).getText('9coywebh'),
                    style: 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),
                          fontSize: limitedHeaderFontSize,
                        ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsetsDirectional.fromSTEB(
                      4.0, 12.0, 16.0, 0.0),
                  child: Text(
                    _model.visitors.length.toString(),
                    style: FlutterFlowTheme.of(context).bodyMedium.override(
                          fontFamily:
                              FlutterFlowTheme.of(context).bodyMediumFamily,
                          letterSpacing: 0.0,
                          useGoogleFonts: GoogleFonts.asMap().containsKey(
                              FlutterFlowTheme.of(context).bodyMediumFamily),
                          fontSize: limitedHeaderFontSize,
                        ),
                  ),
                ),
              ],
            ),
          Expanded(
            child: Builder(
              builder: (context) {
                if (_model.visitors.isNotEmpty) {
                  return Padding(
                    padding: const EdgeInsetsDirectional.fromSTEB(
                        8.0, 8.0, 8.0, 0.0),
                    child: Builder(
                      builder: (context) {
                        final visitor = _model.visitors.map((e) => e).toList();
                        final doc = _model.docs.map((e) => e).toList();
                        return ListView.builder(
                          padding: EdgeInsets.zero,
                          scrollDirection: Axis.vertical,
                          itemCount: visitor.length,
                          itemBuilder: (context, visitorIndex) {
                            final visitorItem = visitor[visitorIndex];
                            final docItem = doc[visitorIndex];
                            return Padding(
                              padding: const EdgeInsetsDirectional.fromSTEB(
                                  0.0, 0.0, 0.0, 1.0),
                              child: InkWell(
                                splashColor: Colors.transparent,
                                focusColor: Colors.transparent,
                                hoverColor: Colors.transparent,
                                highlightColor: Colors.transparent,
                                child: Container(
                                  width: 100.0,
                                  decoration: BoxDecoration(
                                    color: FlutterFlowTheme.of(context)
                                        .primaryBackground,
                                  ),
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        ClipRRect(
                                          borderRadius:
                                              BorderRadius.circular(40.0),
                                          child: CachedNetworkImage(
                                            fadeInDuration: const Duration(
                                                milliseconds: 500),
                                            fadeOutDuration: const Duration(
                                                milliseconds: 500),
                                            imageUrl:
                                                "https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=getFoto&Documento=${getJsonField(
                                              visitorItem,
                                              r'''$.VTE_DOCUMENTO''',
                                            ).toString()}&tipo=E",
                                            width: 60.0,
                                            height: 60.0,
                                            fit: BoxFit.cover,
                                          ),
                                        ),
                                        Expanded(
                                          child: Column(
                                            mainAxisSize: MainAxisSize.max,
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Padding(
                                                padding:
                                                    const EdgeInsetsDirectional
                                                        .fromSTEB(
                                                        12.0, 0.0, 0.0, 0.0),
                                                child: Text(
                                                  valueOrDefault<String>(
                                                    getJsonField(visitorItem,
                                                            r'''$.VTE_NOME''')
                                                        ?.toString(),
                                                    'NOT FOUND',
                                                  ),
                                                  style: FlutterFlowTheme.of(
                                                          context)
                                                      .bodyLarge
                                                      .override(
                                                        fontFamily:
                                                            FlutterFlowTheme.of(
                                                                    context)
                                                                .bodyLargeFamily,
                                                        letterSpacing: 0.0,
                                                        useGoogleFonts: GoogleFonts
                                                                .asMap()
                                                            .containsKey(
                                                                FlutterFlowTheme.of(
                                                                        context)
                                                                    .bodyLargeFamily),
                                                        fontSize:
                                                            limitedBodyFontSize,
                                                      ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                        FlutterFlowIconButton(
                                          borderRadius: 20.0,
                                          borderWidth: 1.0,
                                          buttonSize: 40.0,
                                          icon: Icon(Icons.close,
                                              color:
                                                  FlutterFlowTheme.of(context)
                                                      .customColor6,
                                              size: 20.0),
                                          onPressed: () async {
                                            _model.removeFromVisitors(
                                                visitorItem);
                                            _model.removeFromDocs(docItem);
                                            safeSetState(() {});
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        );
                      },
                    ),
                  );
                } else {
                  return Container(
                    width: 100.0,
                    height: 100.0,
                    decoration: BoxDecoration(
                        color: FlutterFlowTheme.of(context).primaryBackground),
                  );
                }
              },
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: [
              FFButtonWidget(
                onPressed: MediaQuery.of(context).viewInsets.bottom > 0
                    ? () async => await addVisitor(context)
                        .whenComplete(safeSetState(() {}))
                    : () async => await sendVisitors(context),
                text: MediaQuery.of(context).viewInsets.bottom > 0
                    ? FFLocalizations.of(context).getVariableText(
                        enText: 'Add',
                        ptText: 'Adicionar',
                      )
                    : FFLocalizations.of(context).getVariableText(
                        enText: 'Submit',
                        ptText: 'Enviar',
                      ),
                options: FFButtonOptions(
                  width: MediaQuery.of(context).size.width * 0.4,
                  height: 40,
                  padding: const EdgeInsetsDirectional.fromSTEB(
                      24.0, 0.0, 24.0, 0.0),
                  iconPadding:
                      const EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0),
                  color: FlutterFlowTheme.of(context).primary,
                  textStyle: FlutterFlowTheme.of(context).titleSmall.override(
                        fontFamily:
                            FlutterFlowTheme.of(context).titleSmallFamily,
                        color: Colors.white,
                        letterSpacing: 0.0,
                        useGoogleFonts: GoogleFonts.asMap().containsKey(
                            FlutterFlowTheme.of(context).titleSmallFamily),
                        fontSize: limitedInputFontSize,
                      ),
                  elevation: 3.0,
                  borderSide:
                      const BorderSide(color: Colors.transparent, width: 1.0),
                  borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(15),
                      bottomRight: Radius.circular(15),
                      topLeft: Radius.circular(15),
                      topRight: Radius.circular(15)),
                ),
              ),
            ],
          ),
          const SizedBox(height: 30.0)
        ],
      ),
    );
  }

  Future<void> sendVisitors(BuildContext context) async {
    await widget.getVisitors?.call(_model.visitors);
    await widget.getDocs?.call(_model.docs);
    context.pop();
  }

  Future<void> addVisitor(BuildContext context) async {
    safeSetState(() {
      _model.textController?.text = _model.textController.text;
      _model.textController?.selection =
          TextSelection.collapsed(offset: _model.textController!.text.length);
    });
    _model.getVisitorByDoc = await PhpGroup.getVisitorByDocCall.call(
        documento: _model.textController.text.replaceFirst(RegExp(r'^0+'), ''));

    if (PhpGroup.getVisitorByDocCall
                .vistanteId((_model.getVisitorByDoc?.jsonBody ?? '')) !=
            '0' &&
        PhpGroup.getVisitorByDocCall
                .error((_model.getVisitorByDoc?.jsonBody ?? '')) ==
            false &&
        PhpGroup.getVisitorByDocCall
                .vistanteId((_model.getVisitorByDoc?.jsonBody ?? '')) !=
            null) {
      String newDoc =
          _model.textController.text.replaceFirst(RegExp(r'^0+'), '');
      bool existDoc = _model.docs.contains(newDoc);
      if (existDoc == false) {
        _model.addToVisitors(PhpGroup.getVisitorByDocCall
            .visitante((_model.getVisitorByDoc?.jsonBody ?? '')));
        safeSetState(() {});
        _model.addToDocs(
            _model.textController.text.replaceFirst(RegExp(r'^0+'), ''));
        safeSetState(() {});
      } else if (existDoc == true) {
        ToastUtil.showToast(
            message: FFLocalizations.of(context).getVariableText(
                ptText: 'Visitante já adicionado!',
                enText: 'Visitor already added!'),
            gravity: ToastGravity.TOP,
            backgroundColor: Colors.red,
            fontSize: LimitedFontSizeUtil.getBodyFontSize(context));
      }
    } else {
      await showAdaptiveDialog(
        useSafeArea: true,
        context: context,
        builder: (context) {
          return Dialog(
            child:
                VisitorNotFoundComponentWidget(doc: _model.textController.text),
          );
        },
      ).then((value) => safeSetState(() {
            if (value != null) {
              addVisitor(context);
            }
          }));
    }
  }
}
