import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/services.dart';
import 'package:gap/gap.dart';
import '../../ui/theme/app_theme.dart';
import '../../ui/widgets/structure_widgets.dart';
import '../../ui/widgets/action_widgets.dart';
import '../../ui/widgets/input_widgets.dart';
import '../../ui/widgets/visualization_widgets.dart';
import '../../ui/widgets/response_card.dart';
import '../../state/voice_controller.dart';
import '../../state/voice_state.dart';
import '../settings_screen.dart';
import '../../services/tts_service.dart';
import '../../services/firestore_service.dart';
import '../../ui/widgets/voice_shortcuts_guide.dart';

class DecideScreen extends ConsumerStatefulWidget {
  const DecideScreen({super.key});

  @override
  ConsumerState<DecideScreen> createState() => _DecideScreenState();
}

class _DecideScreenState extends ConsumerState<DecideScreen> {
  String _selectedEnergy = "Okay";

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(voiceControllerProvider.notifier).startMonitoring();
      ref.read(voiceControllerProvider.notifier).startProactiveMonitoring();
    });
  }

  final List<Map<String, dynamic>> _categories = [
    {"icon": "🥗", "label": "Food"},
    {"icon": "⏰", "label": "Time"},
    {"icon": "🧘", "label": "Self-care"},
    {"icon": "🏠", "label": "Home"},
    {"icon": "🏃", "label": "Movement"},
    {"icon": "💰", "label": "Spending"},
  ];

  /// Converts technical errors into user-friendly messages
  String _getUserFriendlyError(String? error) {
    if (error == null || error.isEmpty) return "Something went wrong";

    final lowerError = error.toLowerCase();

    if (lowerError.contains('unavailable') ||
        lowerError.contains('microphone')) {
      return "Can't access your microphone. Check permissions?";
    } else if (lowerError.contains('network') ||
        lowerError.contains('connection')) {
      return "Connection issue. I'll try again...";
    } else if (lowerError.contains('timeout')) {
      return "Didn't catch that. Want to try again?";
    } else if (lowerError.contains('no speech') ||
        lowerError.contains('no input')) {
      return "I didn't hear anything. Try speaking closer?";
    }

    return "Oops, something went wrong. Let's try once more?";
  }

  @override
  Widget build(BuildContext context) {
    final session = ref.watch(voiceControllerProvider);
    final voiceState = session.state;
    final ttsService = ref.read(ttsServiceProvider);
    final prefsAsync = ref.watch(preferencesProvider);

    // Speak the response if voice replies are enabled
    ref.listen<VoiceSessionState>(voiceControllerProvider, (previous, next) {
      print(
        "🔵 Voice session changed - has response: ${next.response != null}",
      );
      if (next.response != null && previous?.response != next.response) {
        print("🔵 New response received: ${next.response!.suggestion}");
        // Check if voice replies are enabled
        prefsAsync.whenData((prefs) {
          print("🔵 Voice replies enabled: ${prefs.voiceRepliesEnabled}");
          if (prefs.voiceRepliesEnabled) {
            print("🔊 Triggering TTS to speak");
            ttsService.speak(next.response!.suggestion);
          } else {
            print("🔇 TTS disabled in settings");
          }
        });
      }
    });

    return Column(
      children: [
        // Header
        Padding(
          padding: const EdgeInsets.all(24.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    width: 40,
                    height: 40,
                    decoration: const BoxDecoration(
                      color: AppTheme.energyLow,
                      shape: BoxShape.circle,
                    ),
                    child: const Center(
                      child: Text("🧔", style: TextStyle(fontSize: 24)),
                    ),
                  ),
                  const Gap(12),
                  Text("Hey Ayuel", style: AppTheme.textTheme.displayMedium),
                ],
              ),

              Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.keyboard_voice_outlined),
                    tooltip: 'Voice Shortcuts',
                    onPressed: () {
                      showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,
                        backgroundColor: Colors.transparent,
                        builder: (context) => const VoiceShortcutsGuide(),
                      );
                    },
                  ),
                  IconButton(
                    icon: const Icon(Icons.settings_outlined),
                    onPressed: () {
                      print(
                        "🔵 Settings icon pressed - showing settings sheet",
                      );
                      showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,
                        backgroundColor: Colors.transparent,
                        builder: (context) => DraggableScrollableSheet(
                          initialChildSize: 0.9,
                          minChildSize: 0.5,
                          maxChildSize: 0.95,
                          builder: (_, controller) => Container(
                            decoration: const BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.vertical(
                                top: Radius.circular(20),
                              ),
                            ),
                            child: const SettingsScreen(),
                          ),
                        ),
                      );
                    },
                  ),
                ],
              ),
            ],
          ),
        ),

        Expanded(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24.0),
              child: Column(
                children: [
                  Text("Decide", style: AppTheme.textTheme.displayLarge),
                  const Gap(8),
                  Text(
                    "Pick a category or just ask.",
                    style: AppTheme.textTheme.bodyLarge,
                  ),
                  const Gap(24),

                  AyuelSegmentedEnergy(
                    selected: _selectedEnergy,
                    onChanged: (val) => setState(() => _selectedEnergy = val),
                  ),
                  const Gap(24),

                  GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          crossAxisSpacing: 16,
                          mainAxisSpacing: 16,
                          childAspectRatio: 0.85,
                        ),
                    itemCount: _categories.length,
                    itemBuilder: (context, index) {
                      final cat = _categories[index];
                      return GestureDetector(
                        onTap: () {
                          // Submit a request focused on this category
                          ref
                              .read(voiceControllerProvider.notifier)
                              .submitTextRequest(
                                "Help me with ${cat['label']}",
                                _selectedEnergy,
                              );
                        },
                        child: AyuelCard(
                          padding: const EdgeInsets.all(12),
                          backgroundColor: Colors.white,
                          borderColor: AppTheme.surface,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                width: 48,
                                height: 48,
                                decoration: const BoxDecoration(
                                  color: AppTheme.surface,
                                  shape: BoxShape.circle,
                                ),
                                child: Center(
                                  child: Text(
                                    cat['icon'],
                                    style: const TextStyle(fontSize: 24),
                                  ),
                                ),
                              ),
                              const Gap(8),
                              Text(
                                cat['label'],
                                style: AppTheme.textTheme.bodyMedium?.copyWith(
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                  const Gap(20),
                ],
              ),
            ),
          ),
        ),

        // Voice Interaction Area
        if (session.timerDuration != null)
          Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.only(bottom: 24.0),
              child: AyuelTimer(
                duration: session.timerDuration!,
                onStop: () =>
                    ref.read(voiceControllerProvider.notifier).stopTimer(),
                onFinish: () =>
                    ref.read(voiceControllerProvider.notifier).timerFinished(),
              ),
            ),
          )
        else if (voiceState == VoiceState.speaking && session.response != null)
          Align(
            alignment: Alignment.bottomCenter,
            child: GestureDetector(
              onTap: () {
                // Tap anywhere on response to interrupt and start fresh
                HapticFeedback.mediumImpact();
                ttsService.stop();
                ref.read(voiceControllerProvider.notifier).reset();
              },
              child: AyuelResponseCard(
                query: session.transcript,
                suggestion: session.response!.suggestion,
                actions: session.response!.actions,
                onActionSelected: (action) {
                  HapticFeedback.lightImpact();
                  ref
                      .read(voiceControllerProvider.notifier)
                      .confirmAction(action);
                },
                onCancel: () {
                  HapticFeedback.lightImpact();
                  ref.read(voiceControllerProvider.notifier).cancel();
                },
              ),
            ),
          )
        else
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(32),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 20,
                  offset: const Offset(0, -5),
                ),
              ],
            ),
            child: Column(
              children: [
                if (voiceState == VoiceState.listening ||
                    voiceState == VoiceState.thinking ||
                    voiceState == VoiceState.error) ...[
                  if (voiceState == VoiceState.thinking)
                    const Text(
                      "Thinking...",
                      style: TextStyle(color: AppTheme.textSecondary),
                    )
                  else if (voiceState == VoiceState.error)
                    Column(
                      children: [
                        Text(
                          _getUserFriendlyError(session.error),
                          textAlign: TextAlign.center,
                          style: AppTheme.textTheme.bodyMedium?.copyWith(
                            color: const Color(0xFFD32F2F), // Error red
                          ),
                        ),
                        const Gap(8),
                        TextButton(
                          onPressed: () {
                            HapticFeedback.lightImpact();
                            ref.read(voiceControllerProvider.notifier).reset();
                          },
                          child: const Text("Try Again"),
                        ),
                      ],
                    )
                  else if (voiceState == VoiceState.listening)
                    Column(
                      children: [
                        const AyuelWaveform(isListening: true),
                        const Gap(8),
                        Text(
                          session.transcript.isEmpty
                              ? "Listening..."
                              : session.transcript,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: AppTheme.textTheme.bodyMedium,
                        ),
                      ],
                    ),
                  const Gap(20),
                ],
                AyuelMicButton(
                  state: voiceState,
                  onLongPressStart: () {
                    HapticFeedback.mediumImpact();
                    ref.read(voiceControllerProvider.notifier).startListening();
                  },
                  onLongPressEnd: () {
                    HapticFeedback.lightImpact();
                    ref
                        .read(voiceControllerProvider.notifier)
                        .stopListeningAndThink(_selectedEnergy);
                  },
                  onPressed: () {
                    // Fallback tap
                    if (voiceState == VoiceState.idle ||
                        voiceState == VoiceState.monitoring) {
                      HapticFeedback.mediumImpact();
                      ref
                          .read(voiceControllerProvider.notifier)
                          .startListening();
                    } else if (voiceState == VoiceState.listening) {
                      HapticFeedback.lightImpact();
                      ref
                          .read(voiceControllerProvider.notifier)
                          .stopListeningAndThink(_selectedEnergy);
                    }
                  },
                ),
                const Gap(16),
                if (voiceState == VoiceState.listening)
                  TextButton(
                    onPressed: () =>
                        ref.read(voiceControllerProvider.notifier).cancel(),
                    child: const Text("Cancel"),
                  ),
              ],
            ),
          ),
      ],
    );
  }
}
