import 'package:flutter/material.dart';
import 'package:hub/components/templates_components/details_component/details_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/flutter_flow/flutter_flow_widgets.dart';
import 'package:hub/flutter_flow/form_field_controller.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/flutter_flow/request_manager.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/limited_text_size.dart';
import 'package:share_plus/share_plus.dart';

import '../../shared/utils/validator_util.dart';

class ScheduleCompleteVisitPageModel
    extends FlutterFlowModel<ScheduleComplete> {
  ScheduleCompleteVisitPageModel({this.safeSetState});

  late VoidCallback? safeSetState;
  late Function(Function) updateState;
  final _visitHistoryManager = FutureRequestManager<ApiCallResponse>();
  late final String devUUID;
  late final String cliUUID;
  late final String userUUID;

  late final String? dropdownValue1;
  late final String? dropdownValue2;
  bool? dropDownValidator1;
  bool? dropDownValidator2;
  List<dynamic> visitorJsonList = [];
  String visitorStrList = '0';

  Future<ApiCallResponse> visitHistory({
    String? uniqueQueryKey,
    bool? overrideCache,
    required Future<ApiCallResponse> Function() requestFn,
  }) =>
      _visitHistoryManager.performRequest(
        uniqueQueryKey: uniqueQueryKey,
        overrideCache: overrideCache,
        requestFn: requestFn,
      );
  void clearVisitHistoryCache() => _visitHistoryManager.clear();
  void clearVisitHistoryCacheKey(String? uniqueKey) =>
      _visitHistoryManager.clearRequest(uniqueKey);

  String convertDateFormat(String dateStr) {
    try {
      DateFormat originalFormat = DateFormat('dd/MM/yyyy HH:mm:ss');
      DateFormat newFormat = DateFormat('y-M-d H:mm:ss');

      if (!RegExp(r'^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}$')
          .hasMatch(dateStr)) {
        return 'Invalid date format';
      }

      DateTime dateTime = originalFormat.parse(dateStr);

      String formattedDate = newFormat.format(dateTime);
      return formattedDate;
    } catch (e) {
      return 'Invalid date format';
    }
  }

  void addToVisitorJsonList(dynamic item) => visitorJsonList.add(item);
  void removeFromVisitorJsonList(dynamic item) => visitorJsonList.remove(item);
  void removeAtIndexFromVisitorJsonList(int index) =>
      visitorJsonList.removeAt(index);
  void insertAtIndexInVisitorJsonList(int index, dynamic item) =>
      visitorJsonList.insert(index, item);
  void updateVisitorJsonListAtIndex(int index, Function(dynamic) updateFn) =>
      visitorJsonList[index] = updateFn(visitorJsonList[index]);

  bool isValid() {
    if (textController1!.text.isEmpty ||
        textController2!.text.isEmpty ||
        dropDownValue1 == null ||
        dropDownValue1!.isEmpty ||
        dropDownValue2 == null ||
        dropDownValue2!.isEmpty) {
      return false;
    }

    if (textController1.text.isEmpty) return false;
    if (textController2.text.isEmpty) return false;
    if (dropDownValue1 == null || dropDownValue1!.isEmpty) return false;
    if (dropDownValue2 == null || dropDownValue2!.isEmpty) return false;

    if (visitorStrList == '[]' || visitorJsonList.isEmpty) return false;

    DateTime selectedDateTime1;
    DateTime selectedDateTime2;
    DateTime currentDateTime =
        DateTime.now().subtract(const Duration(minutes: 10));

    try {
      selectedDateTime1 =
          DateFormat('dd/MM/yyyy HH:mm:ss').parse(textController1.text);
      selectedDateTime2 =
          DateFormat('dd/MM/yyyy HH:mm:ss').parse(textController2.text);
    } catch (e) {
      return false;
    }

    if (selectedDateTime2.isBefore(currentDateTime)) {
      return false;
    }

    if (selectedDateTime1.isAfter(selectedDateTime2)) {
      return false;
    }

    if (selectedDateTime1.isAtSameMomentAs(selectedDateTime2)) {
      return false;
    }

    return true;
  }

  final unfocusNode = FocusNode();
  TabController? tabBarController;
  int get tabBarCurrentIndex =>
      tabBarController != null ? tabBarController!.index : 0;

  FocusNode? textFieldFocusNode1;
  TextEditingController? textController1;
  String? Function(BuildContext, String?)? textController1Validator;
  String? _textController1Validator(BuildContext context, String? val) {
    if (val == null || val.isEmpty) {
      return FFLocalizations.of(context).getVariableText(
        enText: 'This field is required.',
        ptText: 'Este campo é obrigatório.',
      );
    }
    if (val != '0') {
      try {
        DateTime startDate = DateFormat('dd/MM/yyyy HH:mm:ss').parse(val);
        DateTime endDate =
            DateFormat('dd/MM/yyyy HH:mm:ss').parse(textController2!.text);
        if (startDate.isAfter(endDate)) {
          return FFLocalizations.of(context).getVariableText(
            ptText: 'A data de início deve ser anterior à data de término.',
            enText: 'Start date must be before end date.',
          );
        }
        if (startDate
            .isBefore(DateTime.now().subtract(const Duration(minutes: 10)))) {
          return FFLocalizations.of(context).getVariableText(
            enText: 'Start date must be after current date.',
            ptText: 'A data de início deve ser posterior à data atual.',
          );
        }
        if (startDate.isAtSameMomentAs(endDate)) {
          return FFLocalizations.of(context).getVariableText(
            enText: 'Start date must be different from end date.',
            ptText: 'A data de início deve ser diferente da data de término.',
          );
        }
      } catch (e) {
        return FFLocalizations.of(context).getVariableText(
            ptText: 'Preencha corretamente o campo de término da visita!',
            enText: 'Fill in the end of visit field correctly!');
      }
    }
    return null;
  }

  DateTime? datePicked1;
  FocusNode? textFieldFocusNode2;
  TextEditingController? textController2;
  String? Function(BuildContext, String?)? textController2Validator;
  String? _textController2Validator(BuildContext context, String? val) {
    if (val == null || val.isEmpty) {
      return FFLocalizations.of(context).getVariableText(
        enText: 'This field is required.',
        ptText: 'Este campo é obrigatório.',
      );
    }
    if (val != '0') {
      try {
        DateTime endDate = DateFormat('dd/MM/yyyy HH:mm:ss').parse(val);
        DateTime startDate =
            DateFormat('dd/MM/yyyy HH:mm:ss').parse(textController1!.text);

        if (endDate.isBefore(startDate)) {
          return FFLocalizations.of(context).getVariableText(
            enText: 'End date must be after start date.',
            ptText: 'A data de término deve ser posterior à data de início.',
          );
        }
        if (startDate
            .isBefore(DateTime.now().subtract(const Duration(minutes: 10)))) {
          return FFLocalizations.of(context).getVariableText(
            enText: 'End date must be after current date.',
            ptText: 'A data de término deve ser posterior à data atual.',
          );
        }
        if (startDate.isAtSameMomentAs(endDate)) {
          return FFLocalizations.of(context).getVariableText(
            enText: 'End date must be different from start date.',
            ptText: 'A data de término deve ser diferente da data de início.',
          );
        }
      } catch (e) {
        return FFLocalizations.of(context).getVariableText(
            ptText: 'Preencha corretamente o campo de início da visita!',
            enText: 'Fill in the visit start field correctly!');
      }
    }
    return null;
  }

  DateTime? datePicked2;
  String? dropDownValue1;
  FormFieldController<String>? dropDownValueController1;

  String? dropDownValue2;
  FormFieldController<String>? dropDownValueController2;
  bool? switchValue;
  FocusNode? textFieldFocusNode3;
  TextEditingController? textController3;
  String? Function(BuildContext, String?)? textController3Validator;
  String? _textController3Validator(BuildContext context, String? val) {
    return null;
  }

  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(BuildContext context) {
    _initVariables();
    tabBarController = TabController(
      vsync: Navigator.of(context),
      length: 2,
    );

    textFieldFocusNode1 = FocusNode();
    textController1 = TextEditingController(
        text: dateTimeFormat(
      'dd/MM/yyyy HH:mm:ss',
      DateTime.now().add(const Duration(minutes: 0)),
    ));
    textController1Validator = _textController1Validator;

    textFieldFocusNode2 = FocusNode();
    textController2 = TextEditingController(
        text: dateTimeFormat(
      'dd/MM/yyyy HH:mm:ss',
      DateTime.now().add(const Duration(days: 1)),
    ));
    textController2Validator = _textController2Validator;

    textFieldFocusNode3 = FocusNode();
    textController3 = TextEditingController();
    textController3Validator = _textController3Validator;

    dropDownValueController1 ??=
        FormFieldController<String>(dropDownValue1 ??= '');
    dropDownValueController2 ??=
        FormFieldController<String>(dropDownValue2 ??= '');
  }

  // Updated variables for dropdowns
  late final List<String> reasonsDropDown1 = [];
  late final List<String> labelsDropDown1 = [];
  late final List<String> optionsDropdown1 = [];

  late final List<String> lavelsDropDown2 = [];
  late final List<String> labelsDropDown2 = [];
  late final List<String> optionsDropdown2 = [];

  // Methods to process dropdown values
  void processDropDown1(List<dynamic> reasonsJsonList) {
    if (dropDownValue1 != null && dropDownValue1!.isNotEmpty) {
      String value = dropDownValue1!;
      if (!(value.contains('{') &&
          value.contains('}') &&
          value.contains(':'))) {
        var item = reasonsJsonList.where((reason) =>
            reason['MOT_DESCRICAO'].toString().contains(dropDownValue1!));
        dropDownValue1 = item.firstOrNull?.toString() ?? '';
        dropDownValueController1?.value = dropDownValue1!;
      }
    }
    reasonsDropDown1.clear();
    reasonsDropDown1.addAll(reasonsJsonList.map((e) => e.toString()).toList());
  }

  void processDropDown2(List<dynamic> lavelList) {
    if (dropDownValue2 != null && dropDownValue2!.isNotEmpty) {
      String value = dropDownValue2!;
      if (!(value.contains('{') &&
          value.contains('}') &&
          value.contains(':'))) {
        var item = lavelList.where((level) =>
            level['NAC_DESCRICAO'].toString().contains(dropDownValue2!));
        dropDownValue2 = item.firstOrNull?.toString() ?? '';
        dropDownValueController2?.value = dropDownValue2!;
      }
    }
    lavelsDropDown2.clear();
    lavelsDropDown2.addAll(lavelList.map((e) => e.toString()).toList());
  }

  @override
  void dispose() {
    unfocusNode.dispose();
    tabBarController?.dispose();
    textFieldFocusNode1?.dispose();
    textController1?.dispose();

    textFieldFocusNode2?.dispose();
    textController2?.dispose();

    textFieldFocusNode3?.dispose();
    textController3?.dispose();

    clearVisitHistoryCache();
  }

  Future changeStatusAction(
    BuildContext context,
    int idDestino,
    int idVisita,
    String accessKey,
    String email,
  ) async {
    // Navigator.pop(context, true);
    context.pop(true);

    bool? blockVisitRequest;
    blockVisitRequest = await visitCancelAction(
      context,
      accessKey: accessKey,
      idDestino: idDestino,
      idVisita: idVisita,
      email: email,
    );
    if (!context.mounted) return;
    if (blockVisitRequest == true) {
      return true;
    } else {
      return false;
    }
  }

  Future<bool> visitCancelAction(BuildContext context,
      {required int? idDestino,
      required int? idVisita,
      required String? accessKey,
      required String? email}) async {
    final ApiCallResponse? response;
    final CancelaVisita callback = PhpGroup.cancelaVisita;

    response = await callback.call(
      idDestino: idDestino,
      idVisita: idVisita,
      AccessKey: accessKey,
      UsuEmail: email,
      DevDesc: '',
    );

    if (response.statusCode == 200) {
      return !response.jsonBody['error'];
    } else {
      return false;
    }
  }

  Future getVisitorsActionPage(
    BuildContext context, {
    List<dynamic>? visitorsJsonList,
  }) async {
    visitorJsonList = visitorsJsonList!.toList().cast<dynamic>();
  }

  Future<bool> toggleCurrentSelectionHeader(
    BuildContext context, {
    required bool? toggleIndexValue,
  }) async {
    if (toggleIndexValue == true) {
      return true;
    }

    return false;
  }

  void switchTab(int index) {
    tabBarController?.animateTo(index);

    safeSetState?.call();
  }

  void setFormField() {
    // if ((visitorStrList != null && visitorStrList != '') &&
    //     ((visitorJsonList != null && (visitorJsonList)!.isNotEmpty) != null)) {
    //   visitorJsonList = visitorJsonList!
    //       .where((e) =>
    //           visitorStrList ==
    //           getJsonField(
    //             e,
    //             r'''$.VTE_DOCUMENTO''',
    //           ).toString().toString())
    //       .toList()
    //       .toList()
    //       .cast<dynamic>();
    //   visitorStrList = visitorStrList!;

    //   safeSetState.call();
    // }

    // if ((dropdownValue1 != null && dropdownValue1 != '') &&
    //     (dropdownValue2 != null && dropdownValue2 != '')) {
    //   dropDownValue1 = dropdownValue1!;
    //   dropDownValue2 = dropdownValue2!;
    //   safeSetState.call();
    // }
  }

  Widget buildVisitDetails({
    required dynamic item,
    required BuildContext context,
    required Future<dynamic> Function(BuildContext, int, int, String, String)
        changeStatusAction,
    required String devUUID,
    required String userUUID,
    required String cliUUID,
    required String cliName,
  }) {
    return DetailsComponentWidget(
      buttons: [
        if (Status.getStatus(item['VAW_STATUS']) ==
            StatusEnum.active) // REJECT ACTION
          FFButtonWidget(
            text: FFLocalizations.of(context).getVariableText(
              ptText: 'Cancelar',
              enText: 'Cancel',
            ),
            icon: const Icon(Icons.close),
            onPressed: () async {
              showAlertDialog(
                  context,
                  FFLocalizations.of(context).getVariableText(
                    ptText: 'Cancelar Visita',
                    enText: 'Cancel Visit',
                  ),
                  FFLocalizations.of(context).getVariableText(
                    ptText: 'Você tem certeza que deseja bloquear essa visita?',
                    enText: 'Are you sure you want to block this visit?',
                  ), () async {
                await changeStatusAction
                    .call(
                  context,
                  int.parse(item['VAW_DESTINO']),
                  int.parse(item['VAW_ID']),
                  item['VAW_CHAVE'] ?? '',
                  item['VTE_DOCUMENTO'] ?? '',
                )
                    .then((value) {
                  // Navigator.pop(context, value);
                  context.pop(value);

                  if (value == false) {
                    showSnackbar(
                      context,
                      FFLocalizations.of(context).getVariableText(
                        enText: 'Error blocking visit',
                        ptText: 'Erro ao bloquear visita',
                      ),
                      true,
                    );
                  } else if (value == true) {
                    showSnackbar(
                      context,
                      FFLocalizations.of(context).getVariableText(
                        enText: 'Success canceling visit',
                        ptText: 'Succeso ao cancelar visita',
                      ),
                      false,
                    );
                  }
                }).catchError((err, stack) {
                  context.pop();
                  showSnackbar(
                    context,
                    FFLocalizations.of(context).getVariableText(
                      enText: 'Error blocking visit',
                      ptText: 'Erro ao bloquear visita',
                    ),
                    true,
                  );
                });
              });
            },
            options: FFButtonOptions(
              width: MediaQuery.of(context).size.width * 0.3,
              height: 40,
              color: FlutterFlowTheme.of(context).primaryBackground,
              elevation: 0,
              textStyle: TextStyle(
                color: FlutterFlowTheme.of(context).primaryText,
                fontSize: LimitedFontSizeUtil.getNoResizeFont(context, 14),
              ),
              borderSide: BorderSide(
                color: FlutterFlowTheme.of(context).primaryBackground,
                width: 1,
              ),
              splashColor: const Color.fromARGB(132, 255, 17, 0),
              // borderRadius: 12,
            ),
          ),
        if (Status.getStatus(item['VAW_STATUS']) !=
            StatusEnum.active) // RECALL ACTION
          FFButtonWidget(
            text: FFLocalizations.of(context).getVariableText(
              ptText: 'Reagendar',
              enText: 'Reschedule',
            ),
            icon: const Icon(Icons.refresh),
            onPressed: () async {
              context.pop();

              dropDownValue1 = item['MOT_DESCRICAO'];
              dropDownValue2 = item['NAC_DESCRICAO'];

              visitorJsonList = [item];
              visitorStrList = item['VTE_DOCUMENTO'];

              switchTab(0);
            },
            options: FFButtonOptions(
              width: MediaQuery.of(context).size.width * 0.5,
              height: 40,
              color: FlutterFlowTheme.of(context).primaryBackground,
              elevation: 0,
              textStyle: TextStyle(
                color: FlutterFlowTheme.of(context).primaryText,
                fontSize: LimitedFontSizeUtil.getNoResizeFont(context, 14),
              ),
              borderSide: BorderSide(
                color: FlutterFlowTheme.of(context).primaryBackground,
                width: 1,
              ),
              splashColor: const Color.fromARGB(137, 134, 134, 134),
              // borderRadius: 12,
            ),
          ),
        if (Status.getStatus(item['VAW_STATUS']) ==
            StatusEnum.active) // SHARE ACTION
          FFButtonWidget(
            text: FFLocalizations.of(context).getVariableText(
              ptText: 'Compartilhar',
              enText: 'Share',
            ),
            icon: const Icon(Icons.share),
            onPressed: () async {
              Share.share('''
Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*$cliName\*.

\*Validade do Convite\*:
- Início: ${item['VAW_DTINICIO']}
- Fim: ${item['VAW_DTFIM']}

URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/$cliUUID/${item['VAW_CHAVE']}
            ''');
            },
            options: FFButtonOptions(
              width: MediaQuery.of(context).size.width * 0.3,
              height: 40,
              color: FlutterFlowTheme.of(context).primaryBackground,
              elevation: 0,
              textStyle: TextStyle(
                color: FlutterFlowTheme.of(context).primaryText,
                fontSize: LimitedFontSizeUtil.getNoResizeFont(context, 14),
              ),
              borderSide: BorderSide(
                color: FlutterFlowTheme.of(context).primaryBackground,
                width: 1,
              ),
              splashColor: const Color.fromARGB(136, 97, 160, 255),
              // borderRadius: 12,
            ),
          ),
      ],
      labelsHashMap: Map<String, String>.from({
        '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
            item['VTE_NOME'] ?? '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Inicio", enText: "Start")}:':
            item['VAW_DTINICIO'] != '' && item['VAW_DTINICIO'] != null
                ? ValidatorUtil.toLocalDateTime(
                    'yyyy-MM-dd HH:mm:ss', item['VAW_DTINICIO'])
                : '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Fim", enText: "End")}:':
            item['VAW_DTFIM'] != '' && item['VAW_DTFIM'] != null
                ? ValidatorUtil.toLocalDateTime(
                    'yyyy-MM-dd HH:mm:ss', item['VAW_DTFIM'])
                : '',
      }),
      imagePath:
          'https://freaccess.com.br/freaccess/getImage.php?cliID=$cliUUID&atividade=getFoto&Documento=${item['VTE_DOCUMENTO'] ?? ''}&tipo=E',
      statusHashMap: [
        if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.active)
          Map<String, Color>.from({
            FFLocalizations.of(context).getVariableText(
              ptText: 'Ativo',
              enText: 'Active',
            ): FlutterFlowTheme.of(context).warning,
          }),
        if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.unknown)
          Map<String, Color>.from({
            FFLocalizations.of(context).getVariableText(
              ptText: 'Pendente',
              enText: 'Pending',
            ): FlutterFlowTheme.of(context).alternate,
          }),
        if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.canceled)
          Map<String, Color>.from({
            FFLocalizations.of(context).getVariableText(
              ptText: 'Cancelado',
              enText: 'Canceled',
            ): FlutterFlowTheme.of(context).error,
          }),
        if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.finished)
          Map<String, Color>.from({
            FFLocalizations.of(context).getVariableText(
              ptText: 'Finalizado',
              enText: 'Finished',
            ): FlutterFlowTheme.of(context).success,
          }),
        if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.blocked)
          Map<String, Color>.from({
            FFLocalizations.of(context).getVariableText(
              ptText: 'Bloqueado',
              enText: 'Blocked',
            ): FlutterFlowTheme.of(context).error,
          }),
        if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.inactive)
          Map<String, Color>.from({
            FFLocalizations.of(context).getVariableText(
              ptText: 'Inativo',
              enText: 'Inactive',
            ): FlutterFlowTheme.of(context).warning,
          }),
      ],
    );
  }
}
