import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:hub/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_model.dart';
import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.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 '/flutter_flow/flutter_flow_theme.dart';

class BottomArrowLinkedLocalsComponentWidget extends StatefulWidget {
  BottomArrowLinkedLocalsComponentWidget({super.key, required this.response});
  ApiCallResponse? response;

  @override
  State<BottomArrowLinkedLocalsComponentWidget> createState() =>
      _BottomArrowLinkedLocalsComponentWidgetState();
}

class _BottomArrowLinkedLocalsComponentWidgetState
    extends State<BottomArrowLinkedLocalsComponentWidget> {
  late BottomArrowLinkedLocalsComponentModel _model;

  bool _loading = false;
  bool _hasData = false;

  late Future<void> _localsFuture;
  List<dynamic> _localsWrap = [];

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

  @override
  void initState() {
    super.initState();
    _model =
        createModel(context, () => BottomArrowLinkedLocalsComponentModel());
    _localsFuture = _fetchLocals();
  }

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

    super.dispose();
  }

  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,
      ),
    );
  }

  Future<ApiCallResponse?> _fetchLocals() async {
    try {
      setState(() => _loading = true);
      widget.response = await PhpGroup.getLocalsCall.call();
      final bool isError = widget.response?.jsonBody['error'];

      if (isError) {
        final String errorMsg = widget.response?.jsonBody['error_msg'];
        await _handleError(context, errorMsg);
        return widget.response;
      }

      final List<dynamic> locals = widget.response?.jsonBody['locais'] ?? [];

      final bool isEmpty = locals.isEmpty;
      final bool isUnique = locals.length == 1;
      final bool isActive = locals[0]['CLU_STATUS'] == 'A';
      final bool isBlocked = locals[0]['CLU_STATUS'] == 'B';

      final bool isEnabled = isUnique && isActive;
      final bool isDisabled = isUnique && isBlocked;

      if (!isEmpty) {
        setState(() {
          _localsWrap.addAll(locals);
          _hasData = true;
          _loading = false;
        });

        if (isDisabled) {
          context.go('/receptionPage');
          return widget.response;
        }
        if (isEnabled) {
          final local = locals[0];

          await StorageHelper()
              .set(ProfileStorageKey.clientName.key, local['CLI_NOME']);
          await StorageHelper()
              .set(ProfileStorageKey.ownerName.key, local['CLU_OWNER_DSC']);
          await StorageHelper()
              .set(ProfileStorageKey.clientUUID.key, local['CLI_ID']);
          await StorageHelper()
              .set(ProfileStorageKey.ownerUUID.key, local['CLU_OWNER_ID']);

          context.pop();
          return widget.response;
        }

        return widget.response;
      }
      _showNoMoreDataSnackBar(context);
      setState(() {
        _hasData = false;
        _loading = false;
      });

      return null;
    } catch (e) {
      setState(() {
        _hasData = false;
        _loading = false;
      });
    }
    return null;
  }

  static Future<void> _handleError(
      BuildContext context, String errorMsg) async {
    await DialogUtil.error(context, errorMsg);
  }

  Future<dynamic> _fetchResponseLink(String status, String cliID) async {
    try {
      await StorageHelper().set(ProfileStorageKey.clientUUID.key, cliID);
      var response = await PhpGroup.resopndeVinculo.call(tarefa: status);

      if (response.jsonBody['error'] == false) {
        return {
          'error': false,
          'error_msg': FFLocalizations.of(context).getVariableText(
              ptText: "Vínculo Ativado com Sucesso",
              enText: "Link Activated Successfully")
        };
      } else {
        await StorageHelper().set(ProfileStorageKey.clientUUID.key, '');
        return response.jsonBody;
      }
    } catch (e, s) {
      await DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          'responderVinculo.php', '', 'Responder Vínculo', e, s);
      return {
        'error': true,
        'error_msg': FFLocalizations.of(context).getVariableText(
            ptText: "Falha ao efetuar operação, Tente Novamente mais tarde.",
            enText: "Failed to perform operation, please try again later.")
      };
    }
  }

  String _imagePath(dynamic local) {
    return 'https://freaccess.com.br/freaccess/Images/Clients/${local['CLI_ID']}.png';
  }

  Map<String, String> _labelsHashMap(dynamic local) {
    return Map<String, String>.from({
      '${local['CLI_PREFIXO']}:': local['CLI_NOME'],
      '${FFLocalizations.of(context).getVariableText(ptText: 'Propriedade', enText: 'Property')}:':
          local['CLU_OWNER_DSC']
    });
  }

  Map<String, Color> _statusHashMap(dynamic local) {
    return Map<String, Color>.from({
      if (local['CLU_STATUS'] == 'A')
        FFLocalizations.of(context).getVariableText(
            ptText: 'Ativo',
            enText: 'Active'): FlutterFlowTheme.of(context).success
      else if (local['CLU_STATUS'] == 'B')
        FFLocalizations.of(context).getVariableText(
            ptText: 'Bloqueado',
            enText: 'Blocked'): FlutterFlowTheme.of(context).error
      else
        FFLocalizations.of(context).getVariableText(
            ptText: 'Pendente',
            enText: 'Pending'): FlutterFlowTheme.of(context).warning
    });
  }

  Widget _item(BuildContext context, dynamic local) {
    log('local: ${local['CLI_NOME']}');
    return CardItemTemplateComponentWidget(
      key: ValueKey<String>(local['CLI_NOME']),
      imagePath: _imagePath(local),
      labelsHashMap: _labelsHashMap(local),
      statusHashMap: [_statusHashMap(local)],
      onTapCardItemAction: () async {
        if (local['CLU_STATUS'] == 'A') {
          await StorageHelper()
              .set(ProfileStorageKey.clientUUID.key, local['CLI_ID']);
          await StorageHelper()
              .set(ProfileStorageKey.clientName.key, local['CLI_NOME']);
          await StorageHelper()
              .set(ProfileStorageKey.ownerName.key, local['CLU_OWNER_DSC']);
          await StorageHelper()
              .set(ProfileStorageKey.ownerUUID.key, local['CLU_OWNER_ID']);

          context.pop(true);
          return true;
        } else if (local['CLU_STATUS'] == 'B') {
          String message = FFLocalizations.of(context).getVariableText(
            ptText:
                'Local Bloqueado para Acesso, Entre em Contato com Administração',
            enText: 'Location Blocked for Access, Contact Administration',
          );

          // if (local['CLU_BLK_MESSAGE'] != null &&
          //     local['CLU_BLK_MESSAGE'] != '') {
          //   message = local['CLU_BLK_MESSAGE'];
          // }

          await DialogUtil.warning(context, message);
          _localsWrap = [];
          _localsFuture = _fetchLocals();
        } else {
          String localName = local['CLI_NOME'];
          showAlertDialog(
            context,
            FFLocalizations.of(context).getVariableText(
                ptText: 'Ativar Vínculo', enText: 'Activate Link'),
            FFLocalizations.of(context).getVariableText(
                ptText: 'Deseja aceitar o vínculo a $localName?',
                enText: 'Do you wish to accept the link to $localName?'),
            () async {
              var response = await _fetchResponseLink('A', local['CLI_ID']);
              context.pop();

              if (response['error'] == true) {
                await DialogUtil.error(context, response['error_msg']);
              } else {
                await DialogUtil.success(context, response['error_msg']);
                setState(() {
                  _localsWrap = [];
                  _localsFuture = _fetchLocals();
                });
              }
            },
          );
        }
      },
    );
  }

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

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.sizeOf(context).height;

    return Align(
      alignment: const AlignmentDirectional(0, 1),
      child: Container(
        width: double.infinity,
        height: height - (height * 0.5),
        decoration: BoxDecoration(
            color: FlutterFlowTheme.of(context).primaryBackground,
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(25), topRight: Radius.circular(25))),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            if (_hasData == false && _loading == false && _localsWrap.isEmpty)
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Center(
                      child: Text(FFLocalizations.of(context).getVariableText(
                          ptText: "Nenhum Local Encontrado.",
                          enText: "No local found")),
                    )
                  ],
                ),
              )
            else if (_hasData == true &&
                _loading == false &&
                _localsWrap.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,
                    ),
                  ),
                ),
              )
          ].addToStart(Padding(
              padding: const EdgeInsets.only(top: 10),
              child: Center(
                  child: Text(
                FFLocalizations.of(context).getVariableText(
                    ptText: 'Escolha um local', enText: 'Choose a location'),
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(fontWeight: FontWeight.bold),
              )))),
        ),
      ),
    );
  }
}
