import 'package:flutter/material.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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart';
import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart';

import 'package:hub/shared/mixins/status_mixin.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/validator_util.dart';

class VisitHistoryWidget extends ScheduleComplete {
  const VisitHistoryWidget({super.key});

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

class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
    with TickerProviderStateMixin, Status {
  late final String devUUID;
  late final String userUUID;
  late final String cliUUID;
  late ScrollController _scrollController;
  int _pageNumber = 1;
  final int _pageSize = 10;
  bool _hasData = false;
  bool _loading = false;
  late ScheduleCompleteVisitPageModel _model;

  late Future<void> _visitFuture;
  List<dynamic> _visitWrap = [];

  Future<void> _initVariables() async {
    devUUID = (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
    userUUID =
        (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
    cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
  }

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

    _model = createModel(
        context,
        () => ScheduleCompleteVisitPageModel(
            safeSetState: () => safeSetState(() {})));
    _initVariables();
    _visitFuture = _fetchVisits();

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

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

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

      var response = await ScheduleCompleteVisitPageModel().visitHistory(
        requestFn: () => PhpGroup.getVisitsCall.call(
          pageSize: _pageSize,
          pageNumber: _pageNumber,
        ),
      );

      final List<dynamic> visits = response.jsonBody['visitas'] ?? [];

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

        return response;
      }

      _showNoMoreDataSnackBar(context);

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

      return null;
    } catch (e, s) {
      await 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++;
      _visitFuture = _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,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    double limitedHeaderFontSize =
        LimitedFontSizeUtil.getHeaderFontSize(context);

    return 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 encontrada!",
                          enText: "No visit found"),
                      style: TextStyle(
                          color: FlutterFlowTheme.of(context).primaryText,
                          fontSize: limitedHeaderFontSize,
                          fontWeight: FontWeight.bold)),
                )
              ],
            ),
          )
        else if (_hasData == true || _pageNumber >= 1)
          Expanded(
              child: FutureBuilder<void>(
            future: _visitFuture,
            builder: (context, snapshot) {
              return ListView.builder(
                  shrinkWrap: true,
                  physics: const BouncingScrollPhysics(),
                  controller: _scrollController,
                  itemCount: _visitWrap.length,
                  itemBuilder: (context, index) {
                    final item = _visitWrap[index];
                    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)),
    );
  }

  Widget _item(BuildContext context, dynamic visitaWrapItem) {
    return CardItemTemplateComponentWidget(
      imagePath:
          'https://freaccess.com.br/freaccess/getImage.php?devUUID=$devUUID&userUUID=$userUUID&cliID=$cliUUID&atividade=getFoto&Documento=${visitaWrapItem['VTE_DOCUMENTO'] ?? ''}&tipo=E',
      labelsHashMap: {
        '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
            visitaWrapItem['VTE_NOME'] ?? '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Inicio", enText: "Start")}:':
            visitaWrapItem['VAW_DTINICIO'] != '' &&
                    visitaWrapItem['VAW_DTINICIO'] != null
                ? ValidatorUtil.toLocalDateTime(
                    'yyyy-MM-dd HH:mm:ss', visitaWrapItem['VAW_DTINICIO'])
                : '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Fim", enText: "End")}:':
            visitaWrapItem['VAW_DTFIM'] != '' &&
                    visitaWrapItem['VAW_DTFIM'] != null
                ? ValidatorUtil.toLocalDateTime(
                    'yyyy-MM-dd HH:mm:ss', visitaWrapItem['VAW_DTFIM'])
                : '',
      },
      statusHashMap: [
        if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == StatusEnum.active)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Ativo',
              enText: 'Active',
            ): FlutterFlowTheme.of(context).warning,
          },
        if (Status.getStatus(visitaWrapItem['VAW_STATUS']) ==
            StatusEnum.finished)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Finalizado',
              enText: 'Finished',
            ): FlutterFlowTheme.of(context).success,
          },
        if (Status.getStatus(visitaWrapItem['VAW_STATUS']) ==
            StatusEnum.unknown)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Desconhecido',
              enText: 'Unknown',
            ): FlutterFlowTheme.of(context).alternate,
          },
        if (Status.getStatus(visitaWrapItem['VAW_STATUS']) ==
            StatusEnum.canceled)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Cancelado',
              enText: 'Canceled',
            ): FlutterFlowTheme.of(context).error,
          },
        if (Status.getStatus(visitaWrapItem['VAW_STATUS']) ==
            StatusEnum.blocked)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Bloqueado',
              enText: 'Blocked',
            ): FlutterFlowTheme.of(context).error,
          },
        if (Status.getStatus(visitaWrapItem['VAW_STATUS']) ==
            StatusEnum.inactive)
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Inativo',
              enText: 'Inactive',
            ): FlutterFlowTheme.of(context).error,
          },
      ],
      onTapCardItemAction: () async {
        final devUUID =
            (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
        final userUUID =
            (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
        final cliUUID =
            (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
        final cliName =
            (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';

        await showDialog(
          useSafeArea: true,
          context: context,
          builder: (context) {
            return Dialog(
              alignment: Alignment.center,
              child: _model.buildVisitDetails(
                item: visitaWrapItem,
                context: context,
                changeStatusAction: _model.changeStatusAction,
                devUUID: devUUID,
                userUUID: userUUID,
                cliUUID: cliUUID,
                cliName: cliName,
              ),
            );
          },
        ).whenComplete(() {
          safeSetState(() {
            _pageNumber = 1;
            _visitWrap = [];
            _visitFuture = _fetchVisits();
          });
        }).catchError((e, s) async {
          await DialogUtil.errorDefault(context);
          LogUtil.requestAPIFailed(
              "proccessRequest.php", "", "Consulta de Visitas", e, s);
          safeSetState(() {
            _hasData = false;
            _loading = false;
          });
        });
      },
    );
  }
}
