import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:trans_lark/entity/history_model.dart';
import 'package:trans_lark/global/speech_to_text_manager.dart';
import 'package:trans_lark/global/translate_manager.dart';
import 'package:trans_lark/hive/history_data.dart';
import 'package:trans_lark/router/get_router.dart';
import 'package:trans_lark/util/t_object_utils.dart';
import 'package:trans_lark/util/t_permission_utils.dart';
import 'package:trans_lark/util/t_print.dart';
import 'package:trans_lark/widget/t_base_easy_loading.dart';
import 'package:trans_lark/widget/t_speak_dialog.dart';

class TranslatorController extends GetxController {
  var textController = TextEditingController();
  var isValue = false.obs;
  var historyList = <HistoryEntity>[].obs;
  var lastWords = '';

  @override
  void onInit() {
    super.onInit();
    _getAllHistory();
  }

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

  _getAllHistory() async {
    historyList.value = HistoryData().getAllHistory().reversed.toList();
  }

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

  Future<void> _onSpeak({String? translation}) async {
    bool micResult = await TPermissionUtils.checkPermission(
      [Permission.microphone],
    );
    if (!micResult) return;
    if (Platform.isIOS) {
      bool speechResult = await TPermissionUtils.checkPermission(
        [Permission.speech],
      );
      if (!speechResult) return;
    }
    await Get.dialog(
      barrierDismissible: true,
      useSafeArea: false,
      TSpeakDialog(
        isListening: SpeechToTextManager().isListening,
        onTap: () async {
          if (!SpeechToTextManager().hasSpeech) {
            await SpeechToTextManager().init();
          }
          if (SpeechToTextManager().hasSpeech) {
            if (SpeechToTextManager().isListening.value) {
              _toTranslatorRes();
            } else {
              SpeechToTextManager().startListening(
                TranslateManager().fromLanguageEntity.value.languageCode,
                _speechRes,
              );
            }
          } else {
            Get.back();
            TBaseEasyLoading.toast('Speech not available');
          }
        },
      ),
    );
    if (Get.isDialogOpen != null && !Get.isDialogOpen!) {
      SpeechToTextManager().stopListening();
    }
  }

  void _speechRes(SpeechRecognitionResult result) {
    TPrint.d('识别结果：${result.recognizedWords}');
    lastWords = result.recognizedWords;
  }

  void _toTranslatorRes() {
    if (TObjectUtils.isEmpty(lastWords)) {
      TBaseEasyLoading.toast('No text recognized');
      return;
    }
    Get.back();
    Get.toNamed(
      GetRouter.translateResult,
      arguments: {"sourceText": lastWords},
    );
  }

  void toHistoryItem(HistoryEntity entity, {int? index}) {
    Get.toNamed(
      GetRouter.translateResult,
      arguments: {
        'sourceText': entity.sourceText,
        'targetText': entity.targetText,
        'isHistory': true,
        'fromLanguage': entity.sourceLanguageName,
        'toLanguage': entity.targetLanguageName,
      },
    );
  }

  void deleteHistoryByIndex(int index, {HistoryEntity? entity}) {
    // 计算原始列表中的对应索引
    int indexToRemoveFromDb = HistoryData().getAllHistory().length - 1 - index;
    historyList.removeAt(indexToRemoveFromDb);
    HistoryData().deleteHistory(indexToRemoveFromDb);
  }

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

  void onTextSubmit(String value) {
    Get.toNamed(
      GetRouter.translateResult,
      arguments: {"sourceText": value},
    );
  }

  void insertHistory(HistoryEntity entity, {int? index}) {
    historyList.insert(0, entity);
  }

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