import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:hub/components/templates_components/provisional_schedule_template/provisional_shcedule_template_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';

class ScheduleProvisionalVisitPageModel
    extends FlutterFlowModel<ScheduleProvisionalVisitPageWidget> {
  String cliUUID = '';
  String devUUID = '';
  String userUUID = '';
  String ownerName = '';
  String ownerUUID = '';
  VoidCallback? setState;

  bool toggleIdx = false;

  List<dynamic> visitors = [];
  void addToVisitors(dynamic item) => visitors.add(item);
  void removeFromVisitors(dynamic item) => visitors.remove(item);
  void removeAtIndexFromVisitors(int index) => visitors.removeAt(index);
  void insertAtIndexInVisitors(int index, dynamic item) =>
      visitors.insert(index, item);
  void updateVisitorsAtIndex(int index, Function(dynamic) updateFn) =>
      visitors[index] = updateFn(visitors[index]);

  List<String> docs = [];
  void addToDocs(String item) => docs.add(item);
  void removeFromDocs(String item) => docs.remove(item);
  void removeAtIndexFromDocs(int index) => docs.removeAt(index);
  void insertAtIndexInDocs(int index, String item) => docs.insert(index, item);
  void updateDocsAtIndex(int index, Function(String) updateFn) =>
      docs[index] = updateFn(docs[index]);

  final formKey = GlobalKey<FormState>();
  FocusNode? personNameFocusNode;
  TextEditingController? personNameTextController;
  String? Function(BuildContext, String?)? personNameTextControllerValidator;
  String? _personNameTextControllerValidator(
      BuildContext context, String? val) {
    if (val == null || val.isEmpty) {
      return FFLocalizations.of(context).getText('3hqg8buh');
    }

    if (val.length > 80) {
      return FFLocalizations.of(context).getText('l0b0zr50');
    }

    return null;
  }

  FocusNode? dateTimeFocusNode;
  TextEditingController? dateTimeTextController;
  String? Function(BuildContext, String?)? dateTimeTextControllerValidator;
  String? _dateTimeTextControllerValidator(BuildContext context, String? val) {
    if (val == null || val.isEmpty) {
      return FFLocalizations.of(context).getText('uzefkuf9');
    }
    DateTime selectedDateTime;
    DateTime currentDateTime = DateTime.now().add(const Duration(minutes: 59));
    selectedDateTime =
        DateFormat('dd/MM/yyyy HH:mm:ss').parse(dateTimeTextController.text);
    try {
      selectedDateTime =
          DateFormat('dd/MM/yyyy HH:mm:ss').parse(dateTimeTextController.text);
    } catch (e) {
      return FFLocalizations.of(context).getVariableText(
        ptText: 'Formato de data inválido',
        enText: 'Invalid date format',
      );
    }
    if (selectedDateTime.isBefore(currentDateTime)) {
      return FFLocalizations.of(context).getVariableText(
        ptText: 'A data devem ser, no mínimo, uma (1) hora à frente.',
        enText: 'The date must be at least one (1) hour ahead.',
      );
    }
    return null;
  }

  DateTime? datePicked;
  FocusNode? notesFocusNode;
  TextEditingController? notesTextController;
  String? Function(BuildContext, String?)? notesTextControllerValidator;
  ApiCallResponse? provVisitSchedule;

  @override
  void initState(BuildContext context) {
    personNameTextControllerValidator = _personNameTextControllerValidator;
    dateTimeTextControllerValidator = _dateTimeTextControllerValidator;

    personNameTextController ??= TextEditingController();
    personNameFocusNode ??= FocusNode();

    dateTimeTextController ??= TextEditingController(
        text: DateFormat('dd/MM/yyyy HH:mm:ss')
            .format(DateTime.now().add(const Duration(days: 1))));
    dateTimeFocusNode ??= FocusNode();

    notesTextController ??= TextEditingController();
    notesFocusNode ??= FocusNode();

    init();
  }

  @override
  void dispose() {
    personNameFocusNode?.dispose();
    personNameTextController?.dispose();

    dateTimeFocusNode?.dispose();
    dateTimeTextController?.dispose();

    notesFocusNode?.dispose();
    notesTextController?.dispose();
  }

  bool isFormValid() {
    if (personNameTextController.text == '' ||
        personNameTextController.text.length > 80) {
      return false;
    }

    if (dateTimeTextController.text == '') {
      return false;
    }

    DateTime selectedDateTime;
    DateTime currentDateTime = DateTime.now().add(const Duration(minutes: 59));
    selectedDateTime =
        DateFormat('dd/MM/yyyy HH:mm:ss').parse(dateTimeTextController.text);

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

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

    return true;
  }

  Future<void> init() async {
    devUUID = (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
    userUUID =
        (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
    cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    ownerName =
        (await StorageHelper().get(ProfileStorageKey.ownerName.key)) ?? '';
    ownerUUID =
        (await StorageHelper().get(ProfileStorageKey.ownerUUID.key)) ?? '';
    setState?.call();
  }
}
