import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart';
import 'package:hub/components/templates_components/details_component/details_component_widget.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/pages/liberation_history/liberation_history_model.dart';
import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/limited_text_size.dart';
import 'package:hub/shared/utils/log_util.dart';
import 'package:hub/shared/utils/snackbar_util.dart';
import 'package:hub/shared/utils/validator_util.dart';

class LiberationHistoryWidget extends StatefulWidget {
  const LiberationHistoryWidget({super.key});

  @override
  State<LiberationHistoryWidget> createState() =>
      _LiberationHistoryWidgetState();
}

class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> {
  late LiberationHistoryModel _model;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  bool _hasData = false;
  bool _loading = false;

  late Future<void> _requestFuture;
  List<dynamic> _requestWrap = [];

  @override
  void initState() {
    _requestFuture = _fetchRequests();
    _model = createModel(context, () => LiberationHistoryModel());

    super.initState();
  }

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

  void onUpdate(BuildContext context) {
    safeSetState(() {});
  }

  String _imagePath(dynamic request) {
    return 'https://freaccess.com.br/freaccess/getImage.php?cliID=${_model.cliUUID}&atividade=getFoto&Documento=${request['VTE_ID'] ?? ''}&tipo=E';
  }

  Map<String, String> _labelsHashMap(dynamic request, bool details) {
    return Map<String, String>.from({
      '${FFLocalizations.of(context).getVariableText(ptText: 'Nome', enText: 'Name')}:':
          request['VTE_NOME'],
      '${FFLocalizations.of(context).getVariableText(ptText: 'Dt. Envio', enText: 'Date Send')}:':
          request['NOT_DTENVIO'] != null
              ? ValidatorUtil.toLocalDateTime(
                  'yyyy-MM-dd HH:mm:ss', request['NOT_DTENVIO'])
              : '',
      '${FFLocalizations.of(context).getVariableText(ptText: 'Motivo', enText: 'Reason')}:':
          request['NOT_MOTIVO'],
      if (details == true)
        '${FFLocalizations.of(context).getVariableText(ptText: 'Mensagem', enText: 'Message')}:':
            request['NOT_MSGENVIO'],
    });
  }

  Map<String, Color> _statusHashMap(dynamic request) {
    return Map<String, Color>.from({
      if (request['NOT_STATUS'] == 'L')
        FFLocalizations.of(context).getVariableText(
            ptText: 'Finalizado',
            enText: 'Finished'): FlutterFlowTheme.of(context).success
      else if (request['NOT_STATUS'] == 'B')
        FFLocalizations.of(context).getVariableText(
            ptText: 'Bloqueado',
            enText: 'Blocked'): FlutterFlowTheme.of(context).error
      else
        FFLocalizations.of(context).getVariableText(
            ptText: 'Ativo',
            enText: 'Active'): FlutterFlowTheme.of(context).warning
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      appBar: _appBar(context),
      body: _body(context),
    );
  }

  PreferredSizeWidget _appBar(BuildContext context) {
    return AppBar(
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      automaticallyImplyLeading: false,
      forceMaterialTransparency: true,
      leading: FlutterFlowIconButton(
        key: ValueKey<String>('BackNavigationAppBar'),
        borderColor: Colors.transparent,
        borderRadius: 30.0,
        borderWidth: 1.0,
        buttonSize: 60.0,
        icon: Icon(
          Icons.keyboard_arrow_left,
          color: FlutterFlowTheme.of(context).primaryText,
          size: 30.0,
        ),
        onPressed: () async {
          context.pop();
        },
      ),
      title: Text(
        FFLocalizations.of(context).getText(
          '784f83pc' /* Histórico de Liberação */,
        ),
        style: FlutterFlowTheme.of(context).headlineMedium.override(
              fontFamily: FlutterFlowTheme.of(context).headlineMediumFamily,
              color: FlutterFlowTheme.of(context).primaryText,
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              letterSpacing: 0.0,
              useGoogleFonts: GoogleFonts.asMap().containsKey(
                  FlutterFlowTheme.of(context).headlineMediumFamily),
            ),
      ),
      actions: const [],
      centerTitle: true,
      elevation: 0.0,
    );
  }

  Widget _body(BuildContext context) {
    return SafeArea(
      top: true,
      child: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          if (_hasData == false && _loading == false && _requestWrap.isEmpty)
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Center(
                    child: Text(FFLocalizations.of(context).getVariableText(
                        ptText: "Nenhuma solicitação encontrada!",
                        enText: "No requests found")),
                  )
                ],
              ),
            )
          else if (_hasData == true &&
              _loading == false &&
              _requestWrap.isNotEmpty)
            Expanded(child: _listItems(context)),
          if (_loading == true)
            Container(
              padding: const EdgeInsets.only(top: 15, bottom: 15),
              child: Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(
                    FlutterFlowTheme.of(context).primary,
                  ),
                ),
              ),
            )
        ],
      ),
    );
  }

  Widget _listItems(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: const BoxDecoration(),
      child: FutureBuilder<void>(
        future: _requestFuture,
        builder: (context, snapshot) {
          return ListView.builder(
            shrinkWrap: true,
            physics: const BouncingScrollPhysics(),
            itemCount: _requestWrap.length,
            itemBuilder: (BuildContext context, int index) {
              final item = _requestWrap[index];
              return _item(context, item);
            },
          );
        },
      ),
    );
  }

  Widget _item(BuildContext context, dynamic liberationHistoryItem) {
    return CardItemTemplateComponentWidget(
      imagePath: _imagePath(liberationHistoryItem),
      labelsHashMap: _labelsHashMap(liberationHistoryItem, false),
      statusHashMap: [_statusHashMap(liberationHistoryItem)],
      onTapCardItemAction: () async {
        showDialog(
          useSafeArea: true,
          context: context,
          builder: (context) {
            return Dialog(
              alignment: Alignment.center,
              child: DetailsComponentWidget(
                labelsHashMap: _labelsHashMap(liberationHistoryItem, true),
                buttons: [
                  if (liberationHistoryItem['NOT_STATUS'] == 'S')
                    FFButtonWidget(
                      text: FFLocalizations.of(context)
                          .getVariableText(ptText: "Aceitar", enText: "Accept"),
                      options: FFButtonOptions(
                        width: 130,
                        height: 40,
                        color: FlutterFlowTheme.of(context).primary,
                        elevation: 0,
                        textStyle: const TextStyle(color: Colors.white),
                        borderSide: BorderSide(
                          color: FlutterFlowTheme.of(context).primaryBackground,
                          width: 1,
                        ),
                        // borderRadius: 12,
                      ),
                      icon: const Icon(Icons.done),
                      onPressed: () async {
                        await _model.answersRequest
                            .call(
                          context: context,
                          ref: liberationHistoryItem['NOT_ID'].toString(),
                          task: 'L',
                          response: '',
                          id: liberationHistoryItem['VTE_ID'].toString(),
                        )
                            .then((value) {
                          if (value) {
                            SnackBarUtil.showSnackBar(
                              context,
                              FFLocalizations.of(context).getVariableText(
                                enText: 'Successfully resolved visit',
                                ptText: 'Visita resolvida com sucesso',
                              ),
                              isError: false,
                            );
                          } else {
                            SnackBarUtil.showSnackBar(
                              context,
                              FFLocalizations.of(context).getVariableText(
                                enText: 'Error resolving visit',
                                ptText: 'Erro ao resolver visita',
                              ),
                              isError: true,
                            );
                          }
                        }).whenComplete(() {
                          safeSetState(() {
                            _requestWrap = [];
                            _requestFuture = _fetchRequests();
                          });

                          context.pop();
                        });
                      },
                    ),
                  if (liberationHistoryItem['NOT_STATUS'] == 'S')
                    FFButtonWidget(
                      text: FFLocalizations.of(context)
                          .getVariableText(ptText: "Bloquear", enText: "Block"),
                      options: FFButtonOptions(
                        width: 130,
                        height: 40,
                        color: FlutterFlowTheme.of(context).error,
                        elevation: 0,
                        textStyle: const TextStyle(color: Colors.white),
                        borderSide: BorderSide(
                          color: FlutterFlowTheme.of(context).primaryBackground,
                          width: 1,
                        ),
                        // borderRadius: 12,
                      ),
                      icon: const Icon(Icons.close),
                      onPressed: () async {
                        await _model.answersRequest
                            .call(
                          context: context,
                          ref: liberationHistoryItem['NOT_ID'].toString(),
                          task: 'B',
                          response: '',
                          id: liberationHistoryItem['VTE_ID'].toString(),
                        )
                            .then((message) {
                          if (message != null || message != '') {
                            showSnackbar(
                              context,
                              FFLocalizations.of(context).getVariableText(
                                enText: 'Successfully resolved visit',
                                ptText: 'Visita resolvida com sucesso',
                              ),
                              false,
                            );
                          } else {
                            showSnackbar(context, message, true);
                          }
                        }).whenComplete(() {
                          safeSetState(() {
                            _requestWrap = [];
                            _requestFuture = _fetchRequests();
                          });
                          context.pop();
                        });
                      },
                    )
                ],
                statusHashMap: [_statusHashMap(liberationHistoryItem)],
                imagePath: _imagePath(liberationHistoryItem),
              ),
            );
          },
        ).then((_) {});
      },
    );
  }

  Future<ApiCallResponse?> _fetchRequests() async {
    try {
      safeSetState(() => _loading = true);
      var response = await PhpGroup.getLiberationsCall.call().first;

      final List<dynamic> requests = response.jsonBody['solicitacoes'] ?? [];

      if (requests.isNotEmpty) {
        safeSetState(() {
          _requestWrap.addAll(requests);
          _hasData = true;
          _loading = false;
        });

        return response;
      }

      _showNoMoreDataSnackBar(context);

      safeSetState(() {
        _hasData = false;
        _loading = false;
      });

      return null;
    } catch (e, s) {
      await DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          "proccessRequest.php", "", "Consulta de Solicitações", e, s);
      safeSetState(() {
        _hasData = false;
        _loading = false;
      });
    }
    return null;
  }

  void _showNoMoreDataSnackBar(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          FFLocalizations.of(context).getVariableText(
              ptText: "Não há mais dados.", enText: "No more data."),
          style: TextStyle(
            color: Colors.white,
            fontSize: LimitedFontSizeUtil.getBodyFontSize(context),
          ),
        ),
        duration: const Duration(seconds: 3),
        backgroundColor: FlutterFlowTheme.of(context).primary,
      ),
    );
  }
}
