import 'package:electronic_assistant/base/base_page.dart';
import 'package:electronic_assistant/data/bean/talks.dart';
import 'package:electronic_assistant/resource/assets.gen.dart';
import 'package:electronic_assistant/resource/colors.gen.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/expand.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../data/bean/talk_original.dart';
import '../common_view.dart';
import 'controller.dart';

class OriginalView extends BasePage<OriginalController> {
  final String? talkId;

  OriginalView(this.talkId, {super.key}) {
    Get.lazyPut(() => OriginalController(talkId), tag: talkId);
  }

  @override
  get controller => Get.find<OriginalController>(tag: talkId);

  @override
  Widget buildBody(BuildContext context) {
    return buildOriginalContentView();
  }

  @override
  bool immersive() {
    return true;
  }

  Widget buildOriginalContentView() {
    return Obx(() {
      if (controller.originalList.isEmpty &&
          controller.talkController.talkBean.value?.status.value ==
              TalkStatus.analysisFail) {
        return getTalkFailView();
      } else if (controller.originalList.isEmpty) {
        return getTalkAnalyseView(
            controller.talkController.isUploading.value == true &&
                    controller.talkController.talkBean.value?.status.value ==
                        TalkStatus.notAnalysis
                ? StringName.talkUploadingFileTip.tr
                : controller
                        .talkController.talkBean.value?.progressContent.value ??
                    '',
            controller.talkController.isUploading.value == true &&
                    controller.talkController.talkBean.value?.status.value ==
                        TalkStatus.notAnalysis
                ? controller.talkController.uploadProgress.value
                : controller.talkController.talkBean.value?.progress.value
                        ?.toDouble() ??
                    0.0);
      } else {
        return ListView.builder(
          padding: EdgeInsets.only(bottom: 150.h),
          itemBuilder: _buildOriginalItem,
          itemCount: controller.originalList.length,
        );
      }
    });
  }

  Widget _buildOriginalItem(BuildContext context, int index) {
    TalkOriginal item = controller.originalList[index];
    return GestureDetector(
      onTap: () {
        controller.talkController.seekTo(item.startMs);
      },
      child: Container(
        color: ColorName.transparent,
        padding:
            EdgeInsets.only(left: 12.w, right: 12.w, top: 11.h, bottom: 13.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 24.w,
              child: Row(
                children: [
                  Container(
                    decoration: const BoxDecoration(
                      color: ColorName.colorPrimary,
                      shape: BoxShape.circle,
                    ),
                    width: 20.w,
                    height: 20.w,
                    child: Center(
                      child: Text(
                        item.speakerId.toString(),
                        style: TextStyle(fontSize: 12.sp, color: Colors.white),
                      ),
                    ),
                  ),
                  SizedBox(width: 6.w),
                  Text(item.speaker.toString(),
                      style: TextStyle(
                          fontSize: 14.sp,
                          color: ColorName.secondaryTextColor)),
                  SizedBox(width: 4.w),
                  Text(formatMilliseconds(item.startMs),
                      style: TextStyle(
                          fontSize: 12.sp, color: ColorName.tertiaryTextColor)),
                  const Spacer(),
                  Obx(() {
                    return Visibility(
                      visible: item.isSelected(),
                      child: GestureDetector(
                        onTap: () {
                          controller.talkTranslateClick(item);
                        },
                        child: Container(
                            margin: EdgeInsets.only(right: 12.w),
                            child: Assets.images.iconTalkTranslate
                                .image(width: 24.w, height: 24.w)),
                      ),
                    );
                  })
                ],
              ),
            ),
            SizedBox(height: 12.h),
            Obx(() {
              return Text(item.sentence.toString(),
                  style: TextStyle(
                      fontSize: 14.sp,
                      color: item.isSelected()
                          ? ColorName.colorPrimary
                          : ColorName.primaryTextColor));
            }),
            Obx(() {
              return Visibility(
                visible:
                    item.getTranslateStatus() == TalkTranslate.translating ||
                        item.getTranslateStatus() == TalkTranslate.translated,
                child: Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 8.w),
                  decoration: BoxDecoration(
                    color: '#FAF9FB'.toColor(),
                    border: Border.all(color: '#F2EFF5'.toColor(), width: 1.w),
                    borderRadius: BorderRadius.circular(6.w),
                  ),
                  padding:
                      EdgeInsets.symmetric(vertical: 11.w, horizontal: 10.w),
                  child: RichText(
                    text: TextSpan(
                      children: [
                        WidgetSpan(
                          alignment: PlaceholderAlignment.middle,
                          child: Container(
                            margin: EdgeInsets.only(right: 6.w),
                            child: Assets.images.iconTalkTranslateSmall
                                .image(width: 22.w, height: 22.w),
                          ),
                        ),
                        TextSpan(
                          text: item.getTranslatedSentence() ??
                              StringName.translating.tr,
                          style: TextStyle(
                              fontSize: 14.sp,
                              color: ColorName.secondaryTextColor),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            })
          ],
        ),
      ),
    );
  }

  String formatMilliseconds(int? totalMilliseconds) {
    if (totalMilliseconds == null) {
      return '';
    }
    int totalSeconds = (totalMilliseconds / 1000).round();
    int hours = totalSeconds ~/ 3600;
    int minutes = (totalSeconds % 3600) ~/ 60;
    int seconds = totalSeconds % 60;

    if (hours > 0) {
      return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    } else {
      return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    }
  }
}
