import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:formularhelden/auswahl_formulare.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:formularhelden/handbuch.dart';
import 'package:formularhelden/impressum.dart';

void main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  await Future.delayed(
    Duration(seconds: 2),
  );
  FlutterNativeSplash.remove();
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    title: 'Sprache',
    home: Sprache(),
  ));
}

class Sprache extends StatefulWidget {
  Sprache({Key? key}) : super(key: key);

  @override
  _SpracheState createState() => _SpracheState();
}

class _SpracheState extends State<Sprache> {
  FlutterTts flutterTts = FlutterTts();
  bool isInitialized = false;
  Completer<void>? speechCompleter;

  List<String> buttonTexts = [
    "Handbuch ansehen",
    "View manual",
    "Rehber bibîne",
    "عرض الدليل",
    "Kılavuzu görüntüle",
    "Переглянути посібник",
    "Просмотреть руководство",
    // Add more texts here
  ];
  int currentTextIndex = 0;
  late Timer _timer;

  List<String> languages = [
    'de-DE',
    'en-US',
    'tr-TR',
    'ar-SA',
    'tr-TR',
    'uk-UA',
    'ru-RU'
  ];
  List<String> texts = [
    'Bitte wählen Sie eine Sprache aus.',
    'Please select a language.',
    'Ji kerema xwe, zimanek hilbijêrin.',
    'يُرجى اختيار لغة',
    'Lütfen bir dil seçin.',
    'Будь ласка, оберіть мову.',
    'Нажмите на украинский флаг, чтобы выбрать русский'
  ];

  int currentIndex = 0;
  String deutsch = 'Deutsch';
  String arabisch = 'Arabisch';
  String englisch = 'Englisch';
  String kurdisch = 'Kurdisch';
  String tuerkisch = 'Türkisch';
  String ukrainisch = 'Ukrainisch';
  String russisch = 'Russisch';
  bool speaking = true;
  bool isSpeechPlaying = true;
  bool showReplayButton = false;
  bool shouldStopSpeech = false;

  @override
  void initState() {
    super.initState();
    // Start the timer to change text every 3 seconds
    _timer = Timer.periodic(Duration(seconds: 3), (timer) {
      setState(() {
        currentTextIndex = (currentTextIndex + 1) % buttonTexts.length;
      });
    });
    // Initialize TTS first, then start speaking
    _initializeTts().then((_) {
      if (mounted) {
        speakTextsSequentially(0);
      }
    });
  }

  Future<void> _initializeTts() async {
    // Set up TTS configuration once at initialization
    await flutterTts.setVolume(1.0);
    await flutterTts.setSpeechRate(0.4);

    // Set up completion listener
    flutterTts.setCompletionHandler(() {
      speechCompleter?.complete();
    });

    // Set up error handler
    flutterTts.setErrorHandler((msg) {
      speechCompleter?.completeError(msg);
    });

    isInitialized = true;
  }

  @override
  void dispose() {
    // Stop speech when the widget is disposed to release resources
    flutterTts.stop();
    _timer.cancel();
    super.dispose();
  }

  Future<void> speakText(String text, String language) async {
    if (!isInitialized || shouldStopSpeech) return;

    try {
      // Ensure any previous speechCompleter is null or complete
      if (speechCompleter?.isCompleted ?? true) {
        speechCompleter = Completer<void>();
      }

      // Set language for the current text
      await flutterTts.setLanguage(language);

      // Start speaking
      await flutterTts.speak(text);

      // Wait for completion or stop
      await speechCompleter?.future;
    } catch (e) {
      print('TTS Error: $e');
    }
  }

  Future<void> speakTextsSequentially(int index) async {
    if (index >= languages.length || !speaking || shouldStopSpeech) {
      setState(() {
        isSpeechPlaying = false;
        showReplayButton = true;
      });
      return;
    }

    try {
      // Speak the current text and wait for completion
      await speakText(texts[index], languages[index]);

      // Check if stop was requested
      if (shouldStopSpeech || !mounted) {
        setState(() {
          isSpeechPlaying = false;
          showReplayButton = true;
        });
        return;
      }

      // Add a small pause between speeches
      await Future.delayed(Duration(milliseconds: 50));

      // Move to the next text if not stopped
      if (mounted && !shouldStopSpeech) {
        await speakTextsSequentially(index + 1);
      }
    } catch (e) {
      print('Sequential TTS Error: $e');
      if (mounted) {
        setState(() {
          isSpeechPlaying = false;
          showReplayButton = true;
        });
      }
    }
  }

  void stopSpeech() {
    if (!isSpeechPlaying) return; // Exit if already stopped

    setState(() {
      shouldStopSpeech = true;
      isSpeechPlaying = false;
      showReplayButton = true;
    });

    // Stop the current TTS speech immediately
    flutterTts.stop();

    // Complete the completer if it hasn't been completed yet
    if (!(speechCompleter?.isCompleted ?? true)) {
      speechCompleter?.complete();
    }
  }

  void replaySpeech() {
    setState(() {
      currentIndex = 0;
      isSpeechPlaying = true;
      showReplayButton = false;
      shouldStopSpeech = false;
    });
    speakTextsSequentially(currentIndex);
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double heightWithoutAppBar = MediaQuery.of(context).size.height -
        (MediaQuery.of(context).padding.top + kToolbarHeight);
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            color: Colors.transparent,
            onPressed: () {},
            icon: Icon(Icons.arrow_circle_left_rounded)),
        systemOverlayStyle: SystemUiOverlayStyle(
          systemNavigationBarColor: Colors.white, // Navigation bar
        ),
        centerTitle: true,
        title: Text('Formularhelden 2.0'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(30),
          child: Column(children: [
            Text(
              'Sprache auswählen | Select language | Ziman hilbijêre | Dil seç | Оберіть мову | اختر اللغة',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: screenWidth * 0.045,
              ),
            ),
            SizedBox(height: heightWithoutAppBar * 0.05),
            Container(
              child: Center(
                child: GridView.count(
                  crossAxisCount: 2,
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  children: [
                    CardButton(
                      imagePath: 'pictures/germany-flag.jpg',
                      buttonText: 'Deutsch',
                      onPressed: () {
                        flutterTts.stop();
                        stopSpeech();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  AuswahlFormulare(value: deutsch)),
                        );
                      },
                    ),
                    CardButton(
                      imagePath: 'pictures/united-kingdom-flag.jpg',
                      buttonText: 'English',
                      onPressed: () {
                        flutterTts.stop();
                        stopSpeech();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  AuswahlFormulare(value: englisch)),
                        );
                      },
                    ),
                    CardButton(
                      imagePath: 'pictures/Kurdistan_flag.jpg',
                      buttonText: 'Kurmancî',
                      onPressed: () {
                        flutterTts.stop();
                        stopSpeech();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  AuswahlFormulare(value: kurdisch)),
                        );
                      },
                    ),
                    CardButton(
                      imagePath: 'pictures/Flag-Egypt.jpg',
                      buttonText: 'اَلْعَرَبِيَّة',
                      onPressed: () {
                        flutterTts.stop();
                        stopSpeech();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  AuswahlFormulare(value: arabisch)),
                        );
                      },
                    ),
                    CardButton(
                      imagePath: 'pictures/turkey-flag-small.jpg',
                      buttonText: 'Türkçe',
                      onPressed: () {
                        flutterTts.stop();
                        stopSpeech();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  AuswahlFormulare(value: tuerkisch)),
                        );
                      },
                    ),
                    CardButton(
                      imagePath: 'pictures/ukraine-flag-medium.jpg',
                      buttonText: 'українська',
                      onPressed: () {
                        flutterTts.stop();
                        stopSpeech();
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: Text(
                                'Оберіть мову | Выберите язык',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.04,
                                ),
                              ),
                              content: SingleChildScrollView(
                                child: Container(
                                  height: heightWithoutAppBar * 0.2,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      TextButton(
                                        onPressed: () async {
                                          Navigator.pop(context);
                                          await Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                                builder: (context) =>
                                                    AuswahlFormulare(
                                                        value: ukrainisch)),
                                          );
                                          setState(() {});
                                        },
                                        child: Text(
                                          'Українська',
                                          style: TextStyle(
                                            fontSize: screenWidth * 0.045,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      TextButton(
                                        onPressed: () async {
                                          Navigator.pop(context);
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                                builder: (context) =>
                                                    AuswahlFormulare(
                                                        value: russisch)),
                                          );
                                          setState(() {});
                                        },
                                        child: Text(
                                          'Російська',
                                          style: TextStyle(
                                            fontSize: screenWidth * 0.045,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              actions: [
                                TextButton(
                                  onPressed: () {
                                    // Handle Close button press
                                    Navigator.pop(context);
                                  },
                                  child: Text(
                                    'Закрити',
                                    style: TextStyle(
                                      fontSize: screenWidth * 0.035,
                                    ),
                                  ),
                                ),
                              ],
                            );
                          },
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: heightWithoutAppBar * 0.03),
            TextButton(
              onPressed: () {
                flutterTts.stop();
                stopSpeech();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => Handbuch(value: deutsch)),
                );
              },
              child: Text(
                buttonTexts[currentTextIndex],
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                  fontSize: screenWidth * 0.045,
                ),
              ),
            ),
            TextButton(
              onPressed: () {
                flutterTts.stop();
                stopSpeech();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => Impressum(value: deutsch)),
                );
              },
              child: Text(
                'Impressum | Legal notice',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                  fontSize: screenWidth * 0.04,
                ),
              ),
            ),
          ]),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.grey.shade800,
        foregroundColor: Colors.white,
        onPressed: isSpeechPlaying
            ? stopSpeech
            : (showReplayButton ? replaySpeech : null),
        tooltip:
            isSpeechPlaying ? 'Stop' : (showReplayButton ? 'Replay' : null),
        child: Icon(
          isSpeechPlaying
              ? Icons.stop
              : (showReplayButton ? Icons.replay : Icons.stop),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30.0),
        ),
      ),
    );
  }
}

class CardButton extends StatelessWidget {
  final String imagePath;
  final String buttonText;
  final VoidCallback onPressed;

  CardButton({
    required this.imagePath,
    required this.buttonText,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double heightWithoutAppBar = MediaQuery.of(context).size.height -
        (MediaQuery.of(context).padding.top + kToolbarHeight);
    return InkWell(
      onTap: onPressed,
      child: Padding(
        padding: EdgeInsets.all(2),
        child: Card(
          color: Color.fromARGB(255, 255, 255, 255),
          elevation: 5,
          shadowColor: Colors.black,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircleAvatar(
                radius: 45,
                backgroundImage: AssetImage(imagePath),
              ),
              SizedBox(height: heightWithoutAppBar * 0.01),
              Text(
                buttonText,
                style: TextStyle(
                    fontSize: screenWidth * 0.04, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Please analyze this code and tell me how to optimize it