// ignore_for_file: unnecessary_overrides

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:IQ/app/modules/home/models/single_ticket.dart';
import 'package:IQ/app/modules/home/models/support_model.dart'
    as support_ticket;
import 'package:IQ/app/modules/home/providers/add_reply_ticket.dart';
import 'package:IQ/app/modules/home/providers/single_ticket_provider.dart';

class SingleTicketController extends GetxController
    with WidgetsBindingObserver {
  final formKey = GlobalKey<FormBuilderState>();
  bool inputsEntered = false;

  // make scroll controller
  final scrollController = ScrollController();
  bool fetchTicketsMessagesData = false;
  // ignore: prefer_typing_uninitialized_variables
  var fetchTicketsMessagesDataVar;
  Future<void> onRefresh() async {
    fetchTicketsMessagesData = false;
    inputsEntered = false;
    singleTicket = null;
    fetchTicketsMessagesDataVar = fetchLoadingSupportTicketsData();
    update();
  }

  final support_ticket.Data ticket = Get.arguments;
  fetchLoadingSupportTicketsData() async {
    await getUserSupportTicketsInforms(ticket.id);
    if (getUserSupportTicketsLoads) {
      fetchTicketsMessagesData = true;
      messages = singleTicket?.data?.messages ?? [];
      // ignore: prefer_is_empty
      if (messages?.length != 0) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          scrollController.animateTo(
            scrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 1000),
            curve: Curves.easeOut,
          );
        });
      }
      update();
    } else {
      fetchTicketsMessagesData = false;
      update();
      Get.snackbar('Error', 'Please try again later');
    }
  }

  sendTicketReply() async {
    String? username = "";
    if ((formKey.currentState?.validate())!) {
      inputsEntered = true;
      update();
      messages?.forEach((element) {
        if (element.userDetails != null) {
          username = element.userDetails?.username;
        }
      });
      await getUserSendReplyTicketInforms(ticket.id, ticketReply);
      if (getUserSendReplyTicketInformsLoads) {
        inputsEntered = false;
        var now = DateTime.now();
        messages?.add(
          Messages(
            message: ticketReply,
            createdAt:
                "${now.year}-${now.month}-${now.day} ${now.hour}:${now.minute}:${now.second}",
            userDetails: UserDetails(username: username),
          ),
        );
        formKey.currentState?.reset();
        update();
        scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      } else {
        inputsEntered = false;
        update();
        Get.snackbar('Error', 'Please try again later');
      }
    } else {
      inputsEntered = false;
      update();
    }
  }

  String? ticketReply;
  onChangeTicketReply(String? ticketReplyInput) {
    ticketReply = ticketReplyInput;
    update();
  }

  List<Messages>? messages = singleTicket?.data?.messages ?? [];

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.inactive ||
        state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) return;
    if (state == AppLifecycleState.resumed) {
      defaultLocale = Platform.localeName.split('_')[0];
      snackBarText = 'back_twice'.tr;
    }
  }

  @override
  void onInit() {
    fetchTicketsMessagesDataVar = fetchLoadingSupportTicketsData();
    WidgetsBinding.instance.addObserver(this);
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
  }
}
