import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/app_style/app_text_style.dart';

class AppTextFormField extends StatefulWidget {
  final Function(String)? onSaved;
  final String? Function(String?)? validator;
  final Function(String)? onChange;
  final bool? obscureText;
  final VoidCallback? showPassword;
  final String? hintText;
  final String? labelText;
  final TextInputType? textInputType;
  final String? initialValue;
  final TextStyle? style;
  final TextStyle? labelStyle;
  final TextStyle? hintStyle;
  final TextStyle? floatingLabelStyle;
  final bool enable;
  final TextAlign? textAlign;
  final FocusNode? node;
  final Widget? suffixIcon;
  final Widget? prefixIcon;
  final IconData? prefixIconData;
  final int? prefixIconSize;
  final TextEditingController? controller;
  final TextInputAction? textInputAction;
  final VoidCallback? onAction;
  final Color? backgroundColor;
  final bool alignLabelWithHint;
  final bool showShadow;
  final bool showBorder;
  final EdgeInsets? contentPadding;
  final bool showWithoutDecoration;
  final VoidCallback? onTap;
  final bool showSpeechToText;
  final Color? enableColor;
  final bool makeMultiLinesNull;
  final bool isBackgroundTransparent;

  const AppTextFormField({
    Key? key,
    this.onSaved,
    this.validator,
    this.node,
    this.onChange,
    this.labelStyle,
    this.obscureText = false, // Provide default value
    this.showPassword,
    this.hintText,
    this.labelText,
    this.hintStyle,
    this.floatingLabelStyle,
    this.textInputType = TextInputType.text,
    this.initialValue, // Provide default value
    this.enable = true,
    this.showSpeechToText = false,
    this.showBorder = true,
    this.style,
    this.contentPadding,
    this.textAlign,
    this.suffixIcon,
    this.prefixIcon,
    this.prefixIconData,
    this.prefixIconSize,
    this.controller,
    this.textInputAction,
    this.onAction,
    this.backgroundColor,
    this.showShadow = true,
    this.showWithoutDecoration = false,
    this.alignLabelWithHint = false, // Provide default value
    this.makeMultiLinesNull = false,
    this.onTap,
    this.isBackgroundTransparent = false,
    this.enableColor,
  }) : super(key: key);

  @override
  State<AppTextFormField> createState() => _AppTextFormFieldState();
}

class _AppTextFormFieldState extends State<AppTextFormField> {
  bool _speechEnabled = false;
  final SpeechToText _speechToText = SpeechToText();
  SettingProvider? _settingProvider;

  late FocusNode _focusNode;

  @override
  void initState() {
    if (widget.initialValue != null) {
      widget.controller?.text = widget.initialValue!;
    }
    _focusNode = widget.node ?? FocusNode();
    if (widget.showSpeechToText) {
      _initSpeech();
    }
    super.initState();
  }

  void _initSpeech() async {
    _speechEnabled = await _speechToText.initialize(
      onError: (SpeechRecognitionError error) async {
        Fluttertoast.showToast(msg: "failed to convert text to speech");
        setState(() {});
      },
    );
  }

  void _startListening() async {
    _speechEnabled = _speechToText.isAvailable;
    if (_speechToText.isListening) {
      Fluttertoast.showToast(msg: "Currently in use");
      return;
    }
    if (!_speechEnabled) return;
    await _speechToText.listen(
        onResult: (SpeechRecognitionResult result) {
          widget.controller?.text = result.recognizedWords;
          if (widget.onChange != null) widget.onChange!(result.recognizedWords);
          widget.controller?.text = result.recognizedWords;
          if (widget.onSaved != null) widget.onSaved!(result.recognizedWords);
          _focusNode.unfocus();
          setState(() {});
        },
        localeId: _settingProvider!.speechToText);
    setState(() {});
  }

  void _stopListening() async {
    await _speechToText.stop();
    _focusNode.unfocus();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    _settingProvider ??= Provider.of(context, listen: false);
    final border = UnderlineInputBorder(
      borderSide: BorderSide.none,
      borderRadius: BorderRadius.circular(16),
    );

    Widget speechToTextWidget = PopupMenuButton<String>(
      child: SizedBox(
        height: 24.toScreenHeight,
        width: 24.toScreenWidth,
        child: "speech_to_text".toSvgAsset(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, height: 24, width: 24),
      ),
      onSelected: (String selectedLanguage) {
        _settingProvider!.setSpeechToText(selectedLanguage);
        _startListening();
      },
      itemBuilder: (BuildContext context) {
        return [
          const PopupMenuItem<String>(
            value: 'ar',
            child: Text('Arabic'),
          ),
          const PopupMenuItem<String>(
            value: 'en',
            child: Text('English'),
          ),
        ];
      },
    );

    final textField = TextFormField(
      focusNode: _focusNode,
      enabled: widget.enable,
      onSaved: (text) {
        if (widget.onSaved != null && text != null) widget.onSaved!(text);
      },
      initialValue: widget.controller != null ? null : widget.initialValue,
      validator: widget.validator,
      onChanged: widget.onChange,
      obscureText: widget.obscureText ?? false,
      keyboardType: widget.textInputType,
      maxLines: widget.makeMultiLinesNull
          ? null
          : widget.textInputType == TextInputType.multiline
              ? 4
              : 1,
      obscuringCharacter: "*",
      controller: widget.controller,
      cursorColor: AppColor.loadingColor(context),
      textInputAction: widget.textInputType == TextInputType.multiline ? null : widget.textInputAction ?? TextInputAction.next,
      onEditingComplete: widget.onAction ?? () => FocusScope.of(context).nextFocus(),
      style: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 14, color: AppColor.textStyleColor(context)),

      // style: widget.style ?? AppTextStyle.body1.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.white10 : AppColor.black10),
      onTap: widget.onTap,
      decoration: InputDecoration(
        alignLabelWithHint: widget.alignLabelWithHint,
        border: border,
        disabledBorder: border,
        focusedBorder: border,
        enabledBorder: border,
        errorBorder: border,
        contentPadding: widget.contentPadding ?? EdgeInsets.symmetric(vertical: 12.toScreenHeight, horizontal: 16.toScreenWidth),
        constraints: const BoxConstraints(),
        suffixIconConstraints: const BoxConstraints(minWidth: 0),
        filled: !widget.isBackgroundTransparent,
        fillColor: widget.isBackgroundTransparent
            ? null
            : !widget.enable?AppColor.disableFieldBackground(context):AppColor.dropDownBackground(context),
        // (context.isDark && !widget.enable
        //         ? AppColor.neutral50
        //         : !widget.enable
        //             ? (widget.enableColor ?? AppColor.disableDark)
        //             : AppColor.dropDownBackground(context)),
        errorStyle: AppTextStyle.tiny.copyWith(color: context.isDark ? AppColor.red50 : AppColor.red30),

        // floatingLabelStyle: widget.floatingLabelStyle ?? AppTextStyle.body1.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.white10 : AppColor.neutral20),

        floatingLabelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: AppColor.floatingTextStyleColor(context)),
        labelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: AppColor.labelTextStyleColor(context)),
        hintText: widget.hintText ?? "",
        // labelText: (widget.showSpeechToText && _speechToText.isListening) ? "Listening..." : widget.labelText ?? "",
        label: Text(
          (widget.showSpeechToText && _speechToText.isListening) ? "Listening..." : widget.labelText ?? "",
        ),
        // labelStyle: widget.labelStyle,
        hintStyle: widget.labelStyle,
        prefixIcon: widget.prefixIcon ??
            (widget.prefixIconData == null
                ? null
                : Icon(
                    widget.prefixIconData,
                    size: widget.prefixIconSize == null ? 20.toScreenWidth : (widget.prefixIconSize! - 10).toScreenWidth,
                    color: AppColor.neutral70,
                  )),
        suffixIcon: widget.suffixIcon ??
            (widget.showSpeechToText
                ? (_speechToText.isListening
                        ? SizedBox(
                            height: 24.toScreenHeight,
                            width: 24.toScreenWidth,
                            child: const Icon(
                              Icons.fiber_manual_record,
                              color: Colors.red,
                            )).onPress(() {
                            // _focusNode.unfocus();
                            _stopListening();
                          })
                        : speechToTextWidget)
                    .paddingOnly(end: 12, bottom: 50)
                : null),
      ),
    );

    if (widget.showWithoutDecoration) return textField;
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16),
          border: widget.showBorder ? Border.all(color: AppColor.border2Color(context), width: 1) : null,
          boxShadow: widget.showShadow ? [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)] : null,
        ),
        child: textField);
  }
}
