import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'dart:io';
import 'dart:math';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:record/record.dart';
import 'package:shared_preferences/shared_preferences.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:typewritertext/typewritertext.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';

class SpeechSampleApp1 extends StatefulWidget {
  const SpeechSampleApp1({Key? key}) : super(key: key);
  @override
  State<SpeechSampleApp1> createState() => _SpeechSampleAppState();
}

/// An example that demonstrates the basic functionality of the
/// SpeechToText plugin for using the speech recognition capability
/// of the underlying platform.

class _SpeechSampleAppState extends State<SpeechSampleApp1> {
  bool _hasSpeech = false;
  bool speech_validate = false;
  bool mute = false;
  final bool _logEvents = false;
  final bool _onDevice = false;
  final FlutterTts ftts = FlutterTts();
  final TextEditingController _pauseForController =
      TextEditingController(text: '5');
  final TextEditingController _listenForController =
      TextEditingController(text: '30');
  double level = 0.0;
  double minSoundLevel = 50000;
  double maxSoundLevel = -50000;
  String lastWords = '';
  String lastError = '';
  String lastStatus = '';
  String _currentLocaleId = '';
  SpeechToText speech = SpeechToText();
  List<Data>? data = [];
  String femalevoice = "cmn-CN-Standard-A";
  String malevoice = "cmn-CN-Standard-B";
  String? userid;
  String zoneValue = '';
  String? textSample = '';
  bool isListening = false;
  final _record = Record();
  bool isRecording = false;
  String? filePath;

  Future<void> _getSharedPreferencesValues() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      //UserId = sharedPreferences.getString('userId');
      userid = sharedPreferences.getString('empId');
      //access = sharedPreferences.getString('access');
    });
  }

  Future<void> startRecording() async {
    if (await Permission.microphone.isGranted) {
      // Directory tempDir = await getTemporaryDirectory();
      // String path = join(tempDir.path, 'temp_audio.mp3');
      // filePath = path;
      //print('Start Recording :$filePath');
      isRecording = true;
      // Check and request for microphone permission
      try {
        if (await _record.hasPermission()) {
          // Start recording
          print('Hitting Karthik');
          await _record.start();
          // await _record.start(
          //   path: filePath!,
          // );
        } else {
          // Handle permission denied
          print("Microphone permission denied");
        }
      } catch (e) {
        print('Error: $e');
      }
    } else {
      // Handle permission denied
      print("Permission not granted");
    }
  }

  Future<void> stopRecording() async {
    //print('Stop Recording :$filePath');
    if (await _record.isRecording()) {
      //await _record.stop();
      try {
        String? path = await _record.stop();
        print('Stop Recording :$path');
        if (path == null) {
          print('Recording path is null');
          return;
        }
        File recordedFile = File(path);
        bool fileExists = await recordedFile.exists();
        print('File exists: $fileExists, Path: $path');
        isRecording = false;
        print('Stop Recording!!!! :$path');
        if (path != null) {
          print('Recording saved to: $path');
          //await sendAudioToWhisperAPI();
          // String res = await RemoteData().getSpeechResponse(path, userid!);
          // print('Response from API :$res');
        }
        //_loadFiles();
      } catch (e) {
        print('Exception : $e');
      }
    }
  }

  // }

  Future<void> requestPermissions() async {
    var status = await Permission.microphone.request();
    var status1 = await Permission.storage.request();
    //var storage = await Permission.storage.request();
    if (status.isGranted) {
      // Permission granted, proceed with recording
      //startRecording();
      print('Sucessfully Granted');
    }
    if (status1.isGranted) {
      // Permission granted, proceed with recording
      //startRecording();
      print('Sucessfully Granted1 ====>');
    } else if (status.isPermanentlyDenied) {
      // Permission permanently denied, open settings to enable
      openAppSettings();
    } else {
      // Handle other cases (e.g., PermissionStatus.restricted)
      print('Microphone permission denied or restricted');
    }
  }

  @override
  void initState() {
    requestPermissions();
    initSpeechState();
    if (Platform.isAndroid) {
      checkAndRequestMicrophonePermission();
    }
    if (Platform.isIOS) {
      //iOS needs to wait until the widget is shown before requesting permission
    }
    if (data!.isNotEmpty) {
      data!.clear();
    }
    _getSharedPreferencesValues();

    //ftts.setVolume(1.0);
    super.initState();
  }

  Future<void> checkAndRequestMicrophonePermission() async {
    PermissionStatus status = await Permission.microphone.status;
    if (status.isGranted) {
      if (kDebugMode) {
        print('Microphone permission is granted.');
      }
    } else {
      status = await Permission.microphone.request();
      if (status.isGranted) {
        if (kDebugMode) {
          print('Microphone permission is granted.');
        }
      } else {
        if (kDebugMode) {
          print('Microphone permission is denied.');
        }
      }
    }
  }

  /// This initializes SpeechToText.That only has to be done
  /// once per application,though calling it again is harmless
  /// it also does nothing.The UX of the sample app ensures that
  /// it can only be called once.

  Future<void> initSpeechState() async {
    _logEvent('Initialize');
    try {
      var hasSpeech = await speech.initialize(
        onError: errorListener,
        onStatus: statusListener,
        debugLogging: _logEvents,
      );
      if (hasSpeech) {
        var systemLocale = await speech.systemLocale();
        _currentLocaleId = systemLocale?.localeId ?? '';
      }
      if (!mounted) return;
      setState(() {
        _hasSpeech = hasSpeech;
      });
    } catch (e) {
      setState(() {
        lastError = 'Speech recognition failed: ${e.toString()}';
        _hasSpeech = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            icon: Image.asset(
              "assets/images/back_arrow.png",
              width: 24,
              height: 24,
              color: Colors.white,
            ),
            //color: Colors.white,
            onPressed: () {
              Navigator.pop(context);
              data!.clear();
              ftts.stop();
            }),

        title: RichText(
          text: const TextSpan(
            children: <TextSpan>[
              TextSpan(
                text: 'SSKL',
                style: Constants.fontStyle,
              ),
              TextSpan(
                text: ' Chat Bot ',
                style: Constants.fontStyle,
              ),
            ],
          ),
        ),
        actions: [
          if (speech_validate)
            IconButton(
              icon: Image.asset(
                "assets/images/stop.png",
                width: 24,
                height: 24,
                color: Colors.white,
              ),
              onPressed: () async {
                ftts.stop();
                setState(() {
                  speech_validate = false;
                });
              },
            ),

          // IconButton(
          //   icon: const Icon(Icons.volume_up),
          //   onPressed: () {
          //     //performAction(isMuted ? TtsAction.unmute : TtsAction.mute);
          //     if (mute) {
          //       const Icon(Icons.volume_mute);
          //       ftts.pause();
          //       mute = false;
          //     } else {
          //       const Icon(Icons.volume_mute);
          //       ftts.speak(zoneValue);
          //       mute = true;
          //     }
          //   },
          // )
          //if (mute)
          IconButton(
            icon: Icon(mute ? Icons.volume_up : Icons.volume_mute),
            onPressed: () {
              setState(() {
                if (mute) {
                  ftts.pause();
                  // Unmute TTS
                  //stopRecording();
                } else {
                  ftts.speak(zoneValue);
                  //startRecording();
                  // Mute TTS
                }
                mute = !mute; // Toggle mute state
              });
            },
          )

          // IconButton(
          //   icon: Image.asset(
          //     "assets/images/stop.png",
          //     width: 24,
          //     height: 24,
          //     color: Colors.white,
          //   ),
          //   onPressed: () async {
          //     setState(() {
          //       if (mute) {
          //         // Mute the FlutterTts
          //         ftts.pause();
          //         mute = false;
          //         print('if ==========> Hitting or not ');
          //       } else {
          //         mute = true;
          //         // Unmute the FlutterTts
          //         ftts.setVolume(1.0);
          //         print('if ==========> Hitting or not ');
          //       }
          //     });
          //   },
          // ),
        ],
        // title: const Text(
        //   'Speech to Text / Text to Speech',
        //   style: Constants.fontStyle,
        // ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      //resizeToAvoidBottomInset: true,
      //resizeToAvoidBottomPadding: false,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image:
                AssetImage('assets/images/bg.png'), // Set your image path here
            fit: BoxFit.cover, // Adjust the image fitting as needed
          ),
          // color: const Color.fromARGB(255, 247, 217, 217),
          // border: Border.all(
          //   style: BorderStyle.solid,
          //   color: const Color.fromARGB(255, 247, 217, 217),
          // ),
          // borderRadius: BorderRadius.circular(0),
        ), // Set the background color for the entire screen
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(children: <Widget>[
                  SpeechControlWidget(
                      lastWords,
                      level,
                      _hasSpeech,
                      speech.isListening,
                      startListening,
                      stopListening,
                      cancelListening,
                      remotevalidate),
                ]),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // This is called each time the users wants to start a new speech
  // recognition session

  void startListening() {
    _logEvent('start listening');
    lastWords = '';
    lastError = '';
    final pauseFor = int.tryParse(_pauseForController.text);
    final listenFor = int.tryParse(_listenForController.text);
    final options = SpeechListenOptions(
        onDevice: _onDevice,
        listenMode: ListenMode.confirmation,
        cancelOnError: true,
        partialResults: true,
        autoPunctuation: true,
        enableHapticFeedback: true);
    // Note that `listenFor` is the maximum, not the minimum, on some
    // systems recognition will be stopped before this value is reached.
    // Similarly `pauseFor` is a maximum not a minimum and may be ignored
    // on some devices.
    speech.listen(
      onResult: resultListener,
      listenFor: Duration(seconds: listenFor ?? 30),
      pauseFor: Duration(seconds: pauseFor ?? 3),
      localeId: _currentLocaleId,
      onSoundLevelChange: soundLevelListener,
      listenOptions: options,
    );
    setState(() {});
  }

  void stopListening() {
    _logEvent('stop');
    speech.stop();
    setState(() {
      level = 0.0;
    });
  }

  void cancelListening() {
    _logEvent('cancel');
    speech.cancel();
    setState(() {
      level = 0.0;
    });
  }

  // This callback is invoked each time new recognition results are
  // available after `listen` is called.
  void resultListener(SpeechRecognitionResult result) {
    _logEvent(
        'Result listener final: ${result.finalResult}, words: ${result.recognizedWords}');
    if (kDebugMode) {
      print(
          '\nTesting listener final: ${result.finalResult}, words: ${result.recognizedWords}');
    }
    setState(() async {
      //lastWords = '${result.recognizedWords} - ${result.finalResult}';
      lastWords = result.recognizedWords;
      if (result.finalResult) {
        if (kDebugMode) {
          print('Final Result: $lastWords');
        }
        //await Future.delayed(Duration.zero);
        remotevalidate(lastWords);
      }
    });
  }

  void soundLevelListener(double level) {
    minSoundLevel = min(minSoundLevel, level);
    maxSoundLevel = max(maxSoundLevel, level);
    // _logEvent('sound level $level: $minSoundLevel - $maxSoundLevel ');
    setState(() {
      this.level = level;
    });
  }

  void errorListener(SpeechRecognitionError error) {
    _logEvent(
        'Received error status: $error, listening: ${speech.isListening}');
    setState(() {
      lastError = '${error.errorMsg} - ${error.permanent}';
    });
  }

  void statusListener(String status) {
    _logEvent(
        'Received listener status: $status, listening: ${speech.isListening}');
    setState(() {
      lastStatus = status;
    });
  }

  //void _switchLang(selectedVal){
  // setState((){
  //  _currentLocaleId = selectedVal;
  // });
  // debugPrint(selectedVal);
  //}

  void _logEvent(String eventDescription) {
    if (_logEvents) {
      var eventTime = DateTime.now().toIso8601String();
      debugPrint('$eventTime $eventDescription');
    }
  }

  Future<void> remotevalidate(String lastWords) async {
    //Constants.showLoader(context);
    if (kDebugMode) {
      print('Hitting from Keyboard or voice !!!!!!!!!!!!$lastWords');
    }
    //String res = await RemoteData().getSpeechResponse(lastWords, userid!);
    String res = await RemoteData().getSpeechResponse(lastWords, userid!);
    //var response = jsonDecode(res);
    Map<String, dynamic> jsonResponse = jsonDecode(res);
    //List<dynamic> output1 = jsonResponse['output1'];
    if (kDebugMode) {
      print('DataFetching $jsonResponse');
    }
    if (jsonResponse.containsKey('error')) {
      //Constants.dismissAlertDialog1(context);
      lastWords = '';
      setState(() {});
      //Constants.showAlertDialog(context, val);
    }
    if (jsonResponse['output'].isNotEmpty) {
      //Constants.dismissAlertDialog1(context);
      //Map<String, dynamic> firstItem = output1[0];
      zoneValue = jsonResponse['output'];
      if (kDebugMode) {
        print('DataFetching1 $zoneValue');
      }
      Data dataInstance =
          Data(question: lastWords, answer: zoneValue, image: 'None');
      await ftts.setLanguage('en-IN');
      //await ftts.setLanguage("en-IN");
      await ftts.setSpeechRate(0.5); //speed of speech
      await ftts.setVolume(1.0); //volume of speech
      await ftts.setPitch(1.2); //pitch of sound
      //Map<String, String> reference = {'setVoice': malevoice};
      if (Platform.isIOS) {
        if (kDebugMode) {
          print(await ftts.getLanguages);
          print(await ftts.getVoices);
        }
        await ftts.setVoice({'name': 'Rishi', 'locale': 'en-IN'});
        //await ftts.setVoice(ftts.getDefaultVoice());
        //await ftts.setIosAudioCategory(
        //[IosTextToSpeechAudioCategory.playAndRecord,
        //IosTextToSpeechAudioCategoryOptions.defaultToSpeaker],
        //);
        await ftts.setIosAudioCategory(
            IosTextToSpeechAudioCategory.playback,
            [
              IosTextToSpeechAudioCategoryOptions.allowBluetooth,
              IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
              IosTextToSpeechAudioCategoryOptions.mixWithOthers,
              IosTextToSpeechAudioCategoryOptions.defaultToSpeaker
            ],
            IosTextToSpeechAudioMode.defaultMode);
      } else {
        await ftts.setVoice({'name': ' Rishi', "locale": "en-IN"});
      }
      //await ftts.setVoice(reference);
      //play text to sp
      var result = await ftts.speak(zoneValue);
      speech_validate = true;
      mute = true;
      if (kDebugMode) {
        print(result);
      }
      if (result == 1) {
        if (kDebugMode) {
          print("Flutter Campus speaking...");
        }
      } else {
        if (kDebugMode) {
          print("Flutter Campus not speaking...");
        }
      }
      if (kDebugMode) {
        print("ZONE value: $zoneValue");
      }
      data!.add(dataInstance);
      ftts.setCompletionHandler(() {
        if (kDebugMode) {
          print('completed for sskl');
        }
        setState(() {
          lastWords = '';
          speech_validate = false;
          //mute = false;
        });
      });
    } else {
      //Constants.dismissAlertDialog1(context);
      if (kDebugMode) {
        print("No items in 'output1'");
      }
    }
    if (kDebugMode) {
      print('Speech Text Resposne =====>$res');
    }
    // Create a list to hold instances of Data
    //List<Data> dataList = [];
    // Add the instance to the list
    SpeechControlWidget.UpdateList(data!);
    setState(() {
      data = data;
    });

    lastWords = '';
    setState(() {});
  }
}

/// Displays the most recently recognized words and the sound level.
class RecognitionResultsWidget extends StatelessWidget {
  const RecognitionResultsWidget({
    Key? key,
    required this.lastWords,
    required this.level,
  }) : super(key: key);

  final String lastWords;
  final double level;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        const Center(
          child: Text(
            'Recognized Words',
            style: TextStyle(fontSize: 22.0),
          ),
        ),
        Expanded(
          child: Stack(
            children: <Widget>[
              Container(
                color: Theme.of(context).secondaryHeaderColor,
                child: Center(
                  child: Text(
                    lastWords,
                    textAlign: TextAlign.start,
                    style: Constants.fontStyle,
                  ),
                ),
              ),
              Positioned.fill(
                bottom: 10,
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    width: 40,
                    height: 40,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                            blurRadius: .26,
                            spreadRadius: level * 1.5,
                            color: Colors.black.withOpacity(.05))
                      ],
                      color: Colors.white,
                      borderRadius: const BorderRadius.all(Radius.circular(50)),
                    ),
                    child: IconButton(
                      icon: const Icon(Icons.mic),
                      onPressed: () {},
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class HeaderWidget extends StatelessWidget {
  const HeaderWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text(
        'Speech recognition available',
        style: TextStyle(fontSize: 22.0),
      ),
    );
  }
}

/// Display the current error status from the speech
/// recognizer
class ErrorWidget extends StatelessWidget {
  const ErrorWidget({
    Key? key,
    required this.lastError,
  }) : super(key: key);

  final String lastError;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        const Center(
          child: Text(
            'Error Status',
            style: TextStyle(fontSize: 22.0),
          ),
        ),
        Center(
          child: Text(lastError),
        ),
      ],
    );
  }
}

/// Controls to start and stop speech recognition
class SpeechControlWidget extends StatelessWidget {
  // final List<Data>? datalist;
  // SpeechControlWidget.withListeners({Key? key, this.datalist}) : super(key: key);
  SpeechControlWidget(
      this.total,
      this.level,
      this.hasSpeech,
      this.isListening,
      this.startListening,
      this.stopListening,
      this.cancelListening,
      this.remoteValidate,
      {Key? key})
      : super(key: key);

  final double level;
  late String? total;
  final bool hasSpeech;
  late final bool isListening;
  final Future<void> Function(String) remoteValidate;
  final void Function() startListening;
  final void Function() stopListening;
  final void Function() cancelListening;
  static List<Data>? data1 = [];
  final TextStyle _textFieldStyle = Constants.LoginbuttonsfontStyle;
  //final TextEditingController _dateTime = TextEditingController();
  late bool isavailable = false;
  bool isTextEntered = false;
  final TextEditingController _textEditingController = TextEditingController();
  String? textSample = '';
  final _record = Record();
  bool isRecording = false;
  String? filePath;

  Future<void> startRecording() async {
    if (await Permission.microphone.isGranted) {
      Directory tempDir = await getTemporaryDirectory();
      String path = join(tempDir.path, 'temp_audio.mp3');
      filePath = path;
      print('Start Recording :$filePath');
      isRecording = true;
      // Check and request for microphone permission
      if (await _record.hasPermission()) {
        // Start recording
        // await _record.start(
        //   const RecordConfig(),
        //   path: filePath!, // by default
        // );
      } else {
        // Handle permission denied
        print("Microphone permission denied");
      }
    } else {
      // Handle permission denied
      print("Permission not granted");
    }
  }

  Future<void> stopRecording() async {
    print('Stop Recording :$filePath');
    if (await _record.isRecording()) {
      await _record.stop();

      if (filePath != null) {
        print('Recording saved to: $filePath');
        //await sendAudioToWhisperAPI();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        SizedBox(
          height: MediaQuery.of(context).size.height * 0.78,
          child: Column(
            children: [
              Expanded(
                child: ListView.builder(
                  itemCount: data1?.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
                      child: SizedBox(
                        width: MediaQuery.of(context).size.width / 1,
                        // Add padding as needed
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            GestureDetector(
                              onLongPress: () {
                                Clipboard.setData(ClipboardData(
                                    text: data1![index].question));
                                Fluttertoast.showToast(
                                  msg: 'Copied',
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.CENTER,
                                  backgroundColor:
                                      const Color.fromARGB(227, 159, 159, 158),
                                  textColor: Colors.white,
                                );
                              },
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    right: 20.0, left: 60.0),
                                child: Container(
                                  padding:
                                      const EdgeInsets.fromLTRB(10, 10, 10, 10),
                                  decoration: const BoxDecoration(
                                    color: Color.fromARGB(255, 238, 177, 64),
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(16.0),
                                      topRight: Radius.circular(0),
                                      bottomLeft: Radius.circular(16.0),
                                      bottomRight: Radius.circular(16.0),
                                    ),
                                  ),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          data1![index].question,
                                          style: Constants.speeachfontStyle,
                                          textAlign: TextAlign.right,
                                          softWrap: true,
                                          maxLines: 4,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                            GestureDetector(
                              onLongPress: () {
                                Clipboard.setData(
                                    ClipboardData(text: data1![index].answer));
                                Fluttertoast.showToast(
                                  msg: 'Copied',
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.CENTER,
                                  backgroundColor:
                                      const Color.fromARGB(227, 159, 159, 158),
                                  textColor: Colors.white,
                                );
                              },
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    right: 60.0, left: 20.0),
                                child: Container(
                                  decoration: const BoxDecoration(
                                    color: Color.fromARGB(255, 239, 242, 247),
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(0),
                                      topRight: Radius.circular(16.0),
                                      bottomLeft: Radius.circular(16.0),
                                      bottomRight: Radius.circular(16.0),
                                    ), // Adjust the value as needed
                                  ),
                                  // Set your desired background color here
                                  padding: const EdgeInsets.all(8.0),

                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      if (data1![index].image != 'None')
                                        Image.memory(
                                          base64Decode(data1![index].image),
                                          fit: BoxFit.cover,
                                          height: 200,
                                          width: 250,
                                        ),
                                      const SizedBox(height: 10),
                                      TypeWriter(
                                          controller: TypeWriterController(
                                            text: data1![index].answer,
                                            duration: const Duration(
                                                milliseconds: 50),
                                          ),
                                          builder: (context, value) {
                                            // Otherwise, render text using HtmlWidget
                                            return HtmlWidget(
                                              value.text,
                                              textStyle: Constants
                                                  .LoginbuttonsfontStyle,
                                            );
                                          }),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(
              horizontal: 5.0), // Adjust the padding as needed
          child: Row(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(
                        10.0), // Set the border radius here
                    color: const Color.fromARGB(255, 255, 255, 255),
                  ),
                  child: TextFormField(
                    controller: _textEditingController,
                    onChanged: (text) {
                      isTextEntered = text.isNotEmpty;
                    },
                    onTap: () {},
                    decoration: const InputDecoration(
                      fillColor: Color.fromARGB(255, 255, 255, 255),
                      contentPadding:
                          EdgeInsets.symmetric(vertical: 15, horizontal: 10),
                      isDense: true,
                      hintText: 'Type Message',
                      border: InputBorder.none,
                    ),
                    style: _textFieldStyle,
                    onFieldSubmitted: (value) {
                      total = _textEditingController.text;
                      if (total != '') {
                        remoteValidate(total!);
                      }
                    },
                    textInputAction: TextInputAction.done,
                  ),
                ),
              ),

              // FloatingActionButton(
              //   onPressed: toggleRecording,
              //   child: Icon(
              //     isListening ? Icons.circle : Icons.mic,
              //     size: 35,
              //   ),
              // ),
              GestureDetector(
                onTap: () {
                  if (_textEditingController.text.isEmpty) {
                    //startListening();

                    startRecording();
                    setState() {
                      isRecording = true;
                    }

                    // Perform action if text is non-empty
                    //toggleRecording();
                  }
                },
                child: IconButton(
                  onPressed: null, // Disable onPressed for IconButton
                  icon: isRecording
                      ? Image.asset(
                          'assets/images/mic.gif', // Replace with your GIF path
                          width: 52,
                          height: 72,
                        )
                      : Image.asset(
                          'assets/images/micicon.png',
                          width: 52,
                          height: 72,
                        ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  static UpdateList(List<Data> dataList) {
    // setState(() {
    //   data = dataList;
    // });
    data1 = dataList;
    print(dataList);
    //data = dataList;
  }
}

class Data {
  String question = ''; // Use camelCase for variable names
  String answer = ''; // Use camelCase for variable names
  String image = '';
  // Constructor
  Data({required this.question, required this.answer, required this.image});
  // Named constructor for creating an instance from a Map
  Data.fromMap(Map<String, dynamic> map)
      : question = map['Question'] ?? '',
        answer = map['Answer'] ?? '',
        image = map['image'] ?? '';
  // Convert the object to a Map
  Map<String, dynamic> toMap() {
    return {
      'Question': question,
      'Answer': answer,
      'image': image,
    };
  }
}

class InitSpeechWidget extends StatelessWidget {
  const InitSpeechWidget(this.hasSpeech, this.initSpeechState, {Key? key})
      : super(key: key);
  final bool hasSpeech;
  final Future<void> Function() initSpeechState;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        TextButton(
          onPressed: hasSpeech ? null : initSpeechState,
          child: const Text('Initialize ...'),
        ),
      ],
    );
  }
}

class SpeechStatusWidget extends StatelessWidget {
  const SpeechStatusWidget({
    Key? key,
    required this.speech,
  }) : super(key: key);

  final SpeechToText speech;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 20),
      color: Theme.of(context).colorScheme.background,
      child: Center(
        child: speech.isListening
            ? const Text(
                "I'm listening...",
                style: TextStyle(fontWeight: FontWeight.bold),
              )
            : const Text(
                'Not listening',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
      ),
    );
  }
}
