import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_translate/ads/interstitial_ad_manage.dart';
import 'package:flutter_translate/common/components/speak_alert.dart';
import 'package:flutter_translate/common/hive/history_data.dart';
import 'package:flutter_translate/common/utils/bot_toast.dart';
import 'package:flutter_translate/common/utils/log_utils.dart';
import 'package:flutter_translate/common/utils/object_utils.dart';
import 'package:flutter_translate/common/utils/permission_utils.dart';
import 'package:flutter_translate/manager/speech_convert.dart';
import 'package:flutter_translate/manager/translate.dart';
import 'package:flutter_translate/model/history_model.dart';
import 'package:flutter_translate/pages/home/home_controller.dart';
import 'package:flutter_translate/router/get_gages.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:speech_to_text/speech_recognition_result.dart';

class TranslatorController extends GetxController {
  var textController = TextEditingController();
  final FocusNode focusNode = FocusNode();
  HomeController homeController = Get.find<HomeController>();
  var isValue = false.obs;
  var historyList = <HistoryModel>[].obs;
  var lastWords = '';

  @override
  void onInit() {
    super.onInit();
    historyList.value = HistoryData().findAll().reversed.toList();
    focusNode.requestFocus();
  }

  @override
  void onClose() {
    textController.dispose();
    super.onClose();
  }

  void onTapBack() {
    focusNode.unfocus();
    InterstitialAdManager().showAdIfReady(
      InterstitialAdManager().adIds[1],
      onTap: () {
        Get.back();
      },
    );
  }

  void onSpeakTranslation() {
    if (isValue.value) {
      textController.text = "";
      isValue.value = false;
    } else {
      speak();
    }
  }

  Future<void> speak() async {
    bool micResult = await PermissionUtils.checkPermission(
      [Permission.microphone],
    );
    if (!micResult) return;
    if (Platform.isIOS) {
      bool speechResult = await PermissionUtils.checkPermission(
        [Permission.speech],
      );
      if (!speechResult) return;
    }
    await Get.dialog(
      barrierDismissible: true,
      useSafeArea: false,
      SpeakAlert(
        isListening: SpeechConvert().isListening,
        onTap: () async {
          if (!SpeechConvert().hasSpeech) {
            await SpeechConvert().init();
          }
          if (SpeechConvert().hasSpeech) {
            if (SpeechConvert().isListening.value) {
              _translatedText();
            } else {
              SpeechConvert().start(
                Translate().fromLanguageEntity.value.code,
                (SpeechRecognitionResult result) {
                  Log.d('识别结果：${result.recognizedWords}');
                  lastWords = result.recognizedWords;
                },
              );
            }
          } else {
            Get.back();
            toast('Speech not available');
          }
        },
      ),
    );
    if (Get.isDialogOpen != null && !Get.isDialogOpen!) {
      SpeechConvert().stop();
    }
  }

  void _translatedText() {
    if (ObjectUtils.isEmpty(lastWords)) {
      toast('No text recognized');
      return;
    }
    Get.back();
    Get.toNamed(
      GetPages.translateText,
      arguments: {"sourceText": lastWords},
    );
  }

  void historyTranslate(HistoryModel historyModel) {
    Get.toNamed(
      GetPages.translateText,
      arguments: {
        'isHistory': true,
        'sourceText': historyModel.sourceText,
        'targetText': historyModel.targetText,
        'fromLanguageName': historyModel.sourceLanguageName,
        'toLanguageName': historyModel.targetLanguageName,
        'fromLanguageCode': historyModel.sourceLanguageCode,
        'toLanguageCode': historyModel.targetLanguageCode,
      },
    );
  }

  void removeHistoryByIndex(int index) {
    // 计算原始列表中的对应索引
    int indexToRemoveFromDb = HistoryData().findAll().length - 1 - index;
    historyList.removeAt(indexToRemoveFromDb);
    HistoryData().remove(indexToRemoveFromDb);
  }

  void changedText(String value) {
    isValue.value = value.trim().isNotEmpty;
  }

  void translatedText(String value) {
    Get.toNamed(
      GetPages.translateText,
      arguments: {"sourceText": value},
    );
  }

  void insertHistory(HistoryModel entity) {
    historyList.insert(0, entity);
  }

  void dropHistory() {
    historyList.clear();
    HistoryData().drop();
  }
}
