import 'dart:io';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:design/design.dart';
import 'package:example/pages/visual/visual_debug_controller.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:guru_widgets/guru_widgets.dart';
import 'package:guru_widgets/button/guru_button.dart';
import 'package:guru_utils/router/router.dart';
import 'package:guru_widgets/theme/guru_theme.dart';
import 'package:guru_utils/log/log.dart';

import 'visual_debug_dialog_controller.dart';
import 'visual_debug_design_model.dart';

/// Created by Haoyi on 2022/8/19
///
///
class TimeUnitTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    Log.d("oldValue:${oldValue.text} newValue:${newValue.text}");

    String newText = newValue.text;
    int offset = newText.indexOf(" ms");
    if (offset == -1) {
      offset = newText.length;
      newText = "$newText ms";
    } else if (offset > 8) {
      newText = oldValue.text;
      offset = oldValue.selection.baseOffset;
    }
    return TextEditingValue(text: newText, selection: TextSelection.collapsed(offset: offset));
  }
}

class VisualDebugDialog extends GetWidget<VisualDebugDialogController> {
  @override
  String? get tag => "VisualDebugDialog";

  final String title;
  final Widget? tips;
  final String? hint;
  final String positiveText;
  final Future<File?> Function()? didPickFile;

  // final String? negativeText;
  // final void Function(String text)? onPositive;
  // final void Function(String text)? onNegative;

  VisualDebugDialogDesignSpec get dialogDesignModel => controller.dialogDesignModel;

  VisualDebugDialog(
      {Key? key,
      this.title = "Visual Debug",
      this.hint = "Duration(ms)",
      this.tips,
      this.positiveText = "ok",
      this.didPickFile})
      : super(key: key) {
    Get.create<VisualDebugDialogController>(() => VisualDebugDialogController(),
        tag: tag, permanent: false);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: FlexibleContainer(
          constraints: BoxConstraints(
              minWidth: dialogDesignModel.measuredSize.width,
              maxWidth: dialogDesignModel.measuredSize.width,
              minHeight: dialogDesignModel.measuredSize.height,
              maxHeight: dialogDesignModel.measuredSize.height + 89),
          radius: dialogDesignModel.radius,
          color: const Color(0xFF252525),
          padding: EdgeInsets.only(bottom: dialogDesignModel.bottomMargin),
          child: DecoratedBox(
              decoration: BoxDecoration(
                borderRadius: dialogDesignModel.radius,
                color: const Color(0xFF252525),
                gradient: const LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Color(0xFF242424), Color(0xFF1D1D1D)]),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  SizedSpacer(height: dialogDesignModel.headerTopSpacing),
                  Align(
                    alignment: AlignmentDirectional.topStart,
                    child: Padding(
                        padding: dialogDesignModel.headerPadding,
                        child: SizedBox(
                          height: dialogDesignModel.headerHeight,
                          child: Stack(
                            children: [
                              Align(
                                alignment: AlignmentDirectional.topStart,
                                child: TapWidget(
                                  onTap: () async {
                                    RouteCenter.instance.back();
                                  },
                                  child: Image.asset(
                                    "assets/images/ic_close.png",
                                    width: dialogDesignModel.closeIconSize,
                                    height: dialogDesignModel.closeIconSize,
                                  ),
                                ),
                              ),
                              Align(
                                alignment: Alignment.bottomCenter,
                                child: AutoSizeText(
                                  title,
                                  minFontSize: 10,
                                  maxLines: 1,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontSize: dialogDesignModel.titleFontSize,
                                      fontWeight: GuruTheme.fwBold,
                                      color: Colors.white),
                                ),
                              )
                            ],
                          ),
                        )),
                  ),
                  SizedSpacer(height: dialogDesignModel.textFieldTopSpacing),
                  FlexibleContainer(
                    height: dialogDesignModel.textFieldHeight,
                    width: dialogDesignModel.buttonSize.width,
                    radius: dialogDesignModel.textFieldRadius,
                    color: Colors.white.withOpacity(0.07),
                    padding: dialogDesignModel.textFieldHorizontalPadding,
                    needClip: true,
                    alignment: AlignmentDirectional.centerStart,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Expanded(
                            flex: 1,
                            child: StreamBuilder<String>(
                                stream: controller.observablePickedUri,
                                builder: (context, snapshot) {
                                  final uri = snapshot.data;
                                  return AutoSizeText(
                                    uri?.isNotEmpty == true ? uri! : "Lottie File Path",
                                    minFontSize: 4,
                                    style: TextStyle(
                                        fontSize: dialogDesignModel.textFieldFontSize,
                                        fontWeight: GuruTheme.fwMedium,
                                        color: Colors.white),
                                  );
                                })),
                        IconButton(
                            icon: const Icon(Icons.animation_outlined),
                            iconSize: 24,
                            color: Colors.white,
                            onPressed: () async {
                              final file = await didPickFile?.call();
                              controller.onPickedFile(file);
                            }),
                      ],
                    ),
                  ),
                  SizedSpacer(height: dialogDesignModel.textFieldTopSpacing),
                  FlexibleContainer(
                    height: dialogDesignModel.textFieldHeight,
                    width: dialogDesignModel.buttonSize.width,
                    radius: dialogDesignModel.textFieldRadius,
                    color: Colors.white.withOpacity(0.07),
                    padding: dialogDesignModel.textFieldHorizontalPadding,
                    needClip: true,
                    alignment: AlignmentDirectional.centerStart,
                    child: TextField(
                        controller: controller.editorController,
                        focusNode: controller.focusNode,
                        showCursor: true,
                        keyboardType: TextInputType.number,
                        // autofocus: true,
                        // maxLengthEnforcement: MaxLengthEnforcement.enforced,
                        // buildCounter: _buildCounter,
                        inputFormatters: [TimeUnitTextInputFormatter()],
                        style: TextStyle(
                            fontSize: dialogDesignModel.textFieldFontSize,
                            fontWeight: GuruTheme.fwMedium,
                            color: Colors.white),
                        maxLines: 1,
                        onChanged: (_) {},
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: hint,
                            hintStyle: TextStyle(
                                fontSize: dialogDesignModel.textFieldFontSize,
                                fontWeight: GuruTheme.fwMedium,
                                color: const Color(0xFF808080))
                            // filled: true,
                            )),
                  ),
                  if (tips != null) ...[
                    SizedSpacer(height: dialogDesignModel.tipsTopSpacing),
                    tips!
                  ],
                  SizedSpacer(height: dialogDesignModel.buttonVerticalSpacing),
                  Row(
                    children: [
                      // if (hasNegative) ...[
                      //   Expanded(
                      //     flex: 1,
                      //     child: Center(
                      //       child: GuruButton(
                      //           size: dialogDesignModel.smallButtonSize,
                      //           style: GuruButtonStyle.negative,
                      //           action: negativeText!,
                      //           onPressed: () async {
                      //             onNegative?.call(controller.text);
                      //           }),
                      //     ),
                      //   ),
                      // ],
                      Expanded(
                        flex: 1,
                        child: Center(
                          child: GuruButton(
                              size: dialogDesignModel.buttonSize,
                              action: positiveText,
                              onPressed: () async {
                                RouteCenter.instance.back(
                                    result: VisualInfo(
                                        type: VisualType.lottie,
                                        uri: controller.currentPickedUri,
                                        duration: Duration(
                                            milliseconds: int.tryParse(controller.text) ?? 1000)));
                                // if (onPositive != null) {
                                //   onPositive?.call(controller.text);
                                // } else {
                                //   RouteCenter.instance.back();
                                // }
                              }),
                        ),
                      ),
                    ],
                  ),
                  SizedSpacer(height: dialogDesignModel.buttonVerticalSpacing),
                ],
              ))),
    );
  }
}
