import 'dart:async';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/manager/interfaces/task.dart';
import 'package:flyinsono/managers/interfaces/entities/urm_dialog_result.dart';
import 'package:get/get.dart';

class LabDialog extends StatefulWidget {
  const LabDialog({
    Key? key,
    required this.title,
    required this.content,
    this.confirmText = "确定",
    this.cancelText = "取消",
    this.maxWidth = 500,
    this.showLoading = false,
    this.showCloseIcon = true,
    this.showCancelButton = true,
    this.confirmLabWidth = 100,
    this.mainTaskCode,
  }) : super(key: key);

  final double confirmLabWidth;
  final String title;
  final String content;
  final String confirmText;
  final String cancelText;
  final String? mainTaskCode;
  final double maxWidth;
  final bool showLoading;
  final bool showCloseIcon;
  final bool showCancelButton;

  @override
  State<StatefulWidget> createState() {
    return LabDialogState();
  }

  static Future<T?> showDialog<T>(
    Widget child, [
    bool barrierDismissible = false,
  ]) async {
    return await Get.dialog<T>(
      child,
      barrierDismissible: barrierDismissible,
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
  }
}

class LabDialogState extends State<LabDialog> {
  Timer? timer;
  static ButtonStyle buttonStyle = ElevatedButton.styleFrom(
    elevation: 0.0,
    backgroundColor: LabColors.dialogHeaderColor,
    padding: EdgeInsets.symmetric(
      horizontal: 12,
      vertical: 5,
    ),
  );

  static const TextStyle buttonTextStyle = TextStyle(
    fontSize: 15,
    height: 1,
    color: LabColors.text200,
  );

  @override
  void initState() {
    if (widget.mainTaskCode != null) {
      timer = Timer.periodic(Duration(seconds: 1), (Timer timer) async {
        MainTaskDTO? serverTaskInfo = await Get.find<IServerTaskManager>()
            .getMainTaskDetailAsync(widget.mainTaskCode ?? '');
        if (serverTaskInfo != null &&
            serverTaskInfo.status == VTaskStatus.Completed) {
          var task = serverTaskInfo.taskDetailList?.first;
          if (task?.result ?? false) {
            timer.cancel();
            Get.back(result: UrmDialogResult.Complate);
          } else {
            timer.cancel();
            Get.back(result: UrmDialogResult.AnalysisFailed);
          }
        }
      });
    }
    super.initState();
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      insetPadding: EdgeInsets.all(0),
      child: Container(
        clipBehavior: Clip.antiAlias,
        constraints: BoxConstraints(maxWidth: widget.maxWidth),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          // border: Border.all(
          //   color: LabColors.dialogHeaderColor,
          //   width: 2,
          //   strokeAlign: 0.0,
          // ),
          color: LabColors.base200,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              color: LabColors.dialogHeaderColor,
              padding: EdgeInsets.symmetric(vertical: 5),
              child: SizedBox(
                height: 40,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(width: 15),
                    Text(
                      widget.title,
                      style: TextStyle(
                        fontSize: 18,
                        color: LabColors.text200,
                      ),
                    ),
                    Expanded(child: Container()),
                    if (widget.showCloseIcon)
                      IconButton(
                        icon: Icon(
                          Icons.close_rounded,
                          color: LabColors.text200,
                          size: 20,
                        ),
                        onPressed: () {
                          Get.back(result: false);
                        },
                      ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 30),
            Align(
              alignment: Alignment.centerLeft,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Row(
                  children: [
                    Text(
                      widget.content,
                      style: TextStyle(
                        fontSize: 18,
                        color: LabColors.text800,
                      ),
                    ),
                    if (widget.showLoading)
                      SizedBox.square(
                        dimension: 40,
                        child: Center(
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: CircularProgressIndicator(
                              strokeWidth: 2.5,
                              color: LabColors.base600,
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 40),
            Container(
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Container(
                    width: widget.confirmLabWidth,
                    child: ElevatedButton(
                      style: buttonStyle,
                      child: Text(widget.confirmText, style: buttonTextStyle),
                      onPressed: () {
                        Get.back(result: true);
                      },
                    ),
                  ),
                  if (widget.showCancelButton) SizedBox(width: 20),
                  if (widget.showCancelButton)
                    Container(
                      width: 100,
                      child: ElevatedButton(
                        style: buttonStyle,
                        child: Text(widget.cancelText, style: buttonTextStyle),
                        onPressed: () {
                          Get.back(result: false);
                        },
                      ),
                    ),
                ],
              ),
            ),
            SizedBox(height: 15),
          ],
        ),
      ),
    );
  }
}
