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/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/pages/visits_on_the_property/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';

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

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

class _VisitsOnThePropertyState extends State<VisitsOnTheProperty>
    with TickerProviderStateMixin {
  late ScrollController _scrollController;

  int _pageNumber = 1;
  bool _hasData = false;
  bool _loading = false;
  int count = 0;
  late final VisitsModel model;

  late Future<void> _future;
  List<dynamic> _list = [];

  @override
  void initState() {
    super.initState();
    model = createModel(
        context, () => VisitsModel(onRefresh: () => safeSetState(() {})));
    _future = _fetchVisits();

    _scrollController = ScrollController()
      ..addListener(() {
        if (_scrollController.position.atEdge &&
            _scrollController.position.pixels != 0) {
          _loadMore();
        }
      });
  }

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

  @override
  Widget build(BuildContext context) {
    late final limitedBodyTextSize =
        LimitedFontSizeUtil.getBodyFontSize(context);
    late final limitedHeaderTextSize =
        LimitedFontSizeUtil.getHeaderFontSize(context);

    return Scaffold(
      appBar: _appBar(context),
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          if (_hasData == false && _pageNumber <= 1 && _loading == false)
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Center(
                    child: Text(
                      FFLocalizations.of(context).getVariableText(
                          ptText: "Nenhuma visita em aberto encontrada!",
                          enText: "No opened visits found"),
                      style: TextStyle(
                        fontFamily: 'Nunito',
                        fontSize: limitedHeaderTextSize,
                      ),
                    ),
                  )
                ],
              ),
            )
          else if (_hasData == true || _pageNumber >= 1)
            Expanded(
                child: FutureBuilder<void>(
              future: _future,
              builder: (context, snapshot) {
                return ListView.builder(
                    shrinkWrap: true,
                    physics: const BouncingScrollPhysics(),
                    controller: _scrollController,
                    itemCount: _list.length + 1,
                    itemBuilder: (context, index) {
                      if (index == 0) {
                        // Add your item here
                        return Padding(
                          padding: const EdgeInsets.only(right: 30, top: 10),
                          child: Text(
                            '',
                            textAlign: TextAlign.right,
                          ),
                        );
                      } else {
                        final item = _list[index - 1];
                        return _item(context, item);
                      }
                    });
              },
            )),
          if (_hasData == true && _loading == true)
            Container(
              padding: const EdgeInsets.only(top: 15, bottom: 15),
              child: Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(
                    FlutterFlowTheme.of(context).primary,
                  ),
                ),
              ),
            )
        ].addToStart(const SizedBox(height: 0)),
      ),
    );
  }

  PreferredSizeWidget _appBar(BuildContext context) {
    return AppBar(
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      automaticallyImplyLeading: false,
      title: Text(
        FFLocalizations.of(context).getVariableText(
          ptText: 'Visitas Abertas',
          enText: 'Opened Visits',
        ),
        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),
            ),
      ),
      leading: _backButton(context, FlutterFlowTheme.of(context)),
      centerTitle: true,
      elevation: 0.0,
      actions: [],
    );
  }

  Widget _backButton(BuildContext context, FlutterFlowTheme theme) {
    return FlutterFlowIconButton(
      key: ValueKey<String>('BackNavigationAppBar'),
      borderColor: Colors.transparent,
      borderRadius: 30.0,
      borderWidth: 1.0,
      buttonSize: 60.0,
      icon: Icon(
        Icons.keyboard_arrow_left,
        color: theme.primaryText,
        size: 30.0,
      ),
      onPressed: () => Navigator.of(context).pop(),
    );
  }

  Future<ApiCallResponse?> _fetchVisits() async {
    try {
      setState(() => _loading = true);

      var response =
          await PhpGroup.getOpenedVisits.call(_pageNumber.toString());

      final List<dynamic> visits = response.jsonBody['visitas'] ?? [];
      safeSetState(() => count = response.jsonBody['total_rows'] ?? 0);

      if (visits.isNotEmpty) {
        setState(() {
          _list.addAll(visits);
          _hasData = true;
          _loading = false;
        });

        return response;
      }

      _showNoMoreDataSnackBar(context);

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

      return null;
    } catch (e, s) {
      DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          "proccessRequest.php", "", "Consulta de Visitas", e, s);
      setState(() {
        _hasData = false;
        _loading = false;
      });
    }
    return null;
  }

  void _loadMore() {
    if (_hasData == true) {
      _pageNumber++;

      _future = _fetchVisits();
    }
  }

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

  Widget _item(BuildContext context, dynamic uItem) {
    return CardItemTemplateComponentWidget(
      imagePath:
          'https://freaccess.com.br/freaccess/getImage.php?devUUID=${model.devUUID}&cliID=${model.cliUUID}&atividade=getFoto&Documento=${uItem['VDO_DOCUMENTO']}&tipo=E',
      labelsHashMap: {
        '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
            uItem['VTA_NOME'] ?? '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Validade", enText: "Valids")}:':
            uItem['VTA_VALIDADE'] ?? '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Motivo", enText: "Reason")}:':
            uItem['MOT_DESCRICAO'][0].toUpperCase() +
                uItem['MOT_DESCRICAO'].substring(1).toLowerCase(),
      },
      statusHashMap: [
        if (uItem['VTA_FIXA'] == true)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Recorrente',
              enText: 'Recurrent',
            ): FlutterFlowTheme.of(context).warning,
          },
        if (uItem['VTA_FIXA'] == false)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Única',
              enText: 'Single',
            ): FlutterFlowTheme.of(context).success,
          },
      ],
      onTapCardItemAction: () async {
        await showDialog(
          useSafeArea: true,
          context: context,
          builder: (context) {
            return Dialog(
              alignment: Alignment.center,
              child: model.buildVisitDetails(
                item: uItem,
                context: context,
                model: model,
              ),
            );
          },
        ).whenComplete(() {
          safeSetState(() {
            _pageNumber = 1;
            _list = [];
            _future = _fetchVisits()
                .then((value) => value!.jsonBody['visitas'] ?? []);
          });
        }).catchError((e, s) {
          DialogUtil.errorDefault(context);
          LogUtil.requestAPIFailed(
              "proccessRequest.php", "", "Consulta de Visitas", e, s);
          safeSetState(() {
            _hasData = false;
            _loading = false;
          });
        });
      },
    );
  }
}
