import 'package:flutter_tts/flutter_tts.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'tts_service_web.dart' if (dart.library.io) 'tts_service_stub.dart';

final ttsServiceProvider = Provider<TtsService>((ref) => TtsService());

class TtsService {
  final FlutterTts _flutterTts = FlutterTts();
  bool _isInitialized = false;

  Future<void> _initialize() async {
    if (_isInitialized) return;

    try {
      if (!kIsWeb) {
        // Configure TTS settings for mobile platforms
        await _flutterTts.setLanguage("en-US");

        // More natural speech rate (slightly slower for clarity)
        await _flutterTts.setSpeechRate(0.52);

        await _flutterTts.setVolume(1.0);

        // Natural pitch
        await _flutterTts.setPitch(1.0);

        // Try to select a natural-sounding voice
        await _selectNaturalVoice();
      }

      _isInitialized = true;
      print('✅ TTS initialized (web: $kIsWeb)');
    } catch (e) {
      print('❌ Error initializing TTS: $e');
    }
  }

  /// Selects the most natural-sounding voice for mobile platforms
  Future<void> _selectNaturalVoice() async {
    try {
      final voices = await _flutterTts.getVoices;

      if (voices == null || voices.isEmpty) {
        print('⚠️ No voices available, using default');
        return;
      }

      print('🎤 Available voices: ${voices.length}');

      // Priority order for natural voices on mobile:
      // iOS: Premium/Enhanced voices
      // Android: Google TTS voices
      final voicePriorities = [
        // iOS Premium Enhanced Voices
        'Samantha (Enhanced)',
        'Alex (Enhanced)',
        'Victoria (Enhanced)',
        'Karen (Enhanced)',
        'Moira (Enhanced)',
        'Tessa (Enhanced)',

        // iOS Premium Voices (non-enhanced)
        'Samantha',
        'Alex',
        'Victoria',
        'Karen',

        // Android Google voices
        'en-us-x-tpf-network', // Female neural
        'en-us-x-tpm-network', // Male neural
        'en-us-x-iob-network', // Female neural
        'en-us-x-iom-network', // Male neural
        'en-us-x-sfg-network', // High quality
        // Fallback patterns
        'Enhanced',
        'Premium',
        'en-US',
      ];

      // Try to find the best voice
      for (final priority in voicePriorities) {
        final matchingVoice = voices.firstWhere((voice) {
          final name = voice.toString().toLowerCase();
          return name.contains(priority.toLowerCase()) && name.contains('en');
        }, orElse: () => null);

        if (matchingVoice != null) {
          await _flutterTts.setVoice({
            "name": matchingVoice.toString(),
            "locale": "en-US",
          });
          print('✅ Selected natural voice: $matchingVoice');
          return;
        }
      }

      print('⚠️ Using default voice');
    } catch (e) {
      print('❌ Error selecting natural voice: $e');
    }
  }

  Future<void> speak(String text) async {
    await _initialize();

    try {
      print('🔊 TTS attempting to speak: "$text" (web: $kIsWeb)');

      if (kIsWeb) {
        // Use Web Speech API for web
        speakWeb(text);
      } else {
        // Use flutter_tts for mobile
        await _flutterTts.speak(text);
      }

      print('✅ TTS speak command sent');
    } catch (e) {
      print('❌ Error speaking: $e');
    }
  }

  Future<void> stop() async {
    try {
      if (kIsWeb) {
        stopWeb();
      } else {
        await _flutterTts.stop();
      }
    } catch (e) {
      print('Error stopping TTS: $e');
    }
  }

  void dispose() {
    if (kIsWeb) {
      stopWeb();
    } else {
      _flutterTts.stop();
    }
  }
}
