import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.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';

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

  @override
  ConsumerState<TodayScreen> createState() => _TodayScreenState();
}

class _TodayScreenState extends ConsumerState<TodayScreen> {
  String _selectedEnergy = "Okay";

  @override
  Widget build(BuildContext context) {
    final session = ref.watch(voiceControllerProvider);
    final voiceState = session.state;

    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),
                ],
              ),
              IconButton(icon: const Icon(Icons.settings), onPressed: () {}),
            ],
          ),
        ),

        Expanded(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24.0),
              child: Column(
                children: [
                  const Gap(10),
                  // Energy Selector
                  AyuelSegmentedEnergy(
                    selected: _selectedEnergy,
                    onChanged: (val) => setState(() => _selectedEnergy = val),
                  ),
                  const Gap(20),

                  Text(
                    "Talk to Ayuel",
                    style: AppTheme.textTheme.displayLarge,
                    textAlign: TextAlign.center,
                  ),
                  const Gap(8),
                  Text(
                    "You can use voice anytime.\nWant to try it now?",
                    style: AppTheme.textTheme.bodyLarge,
                    textAlign: TextAlign.center,
                  ),
                  const Gap(40),

                  // Suggestions
                  _SuggestionItem(
                    text: "Help me plan my day",
                    energy: _selectedEnergy,
                  ),
                  const Gap(12),
                  _SuggestionItem(
                    text: "Quick 5-minute reset",
                    energy: _selectedEnergy,
                  ),
                  const Gap(12),
                  _SuggestionItem(
                    text: "Review my focus areas",
                    energy: _selectedEnergy,
                  ),
                  const Gap(12),
                  _SuggestionItem(
                    text: "I'm feeling overwhelmed...",
                    energy: _selectedEnergy,
                  ),

                  const Gap(40),
                ],
              ),
            ),
          ),
        ),

        // 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: AyuelResponseCard(
              query: session.transcript,
              suggestion: session.response!.suggestion,
              actions: session.response!.actions,
              onActionSelected: (action) {
                ref
                    .read(voiceControllerProvider.notifier)
                    .confirmAction(action);
              },
              onCancel: () =>
                  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(
              mainAxisSize: MainAxisSize.min,
              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)
                    Text(
                      session.error ?? "Error",
                      style: const TextStyle(color: Colors.red),
                    )
                  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),
                ],

                // Mic Button with Press and Hold logic
                AyuelMicButton(
                  state: voiceState,
                  onLongPressStart: () {
                    ref.read(voiceControllerProvider.notifier).startListening();
                  },
                  onLongPressEnd: () {
                    ref
                        .read(voiceControllerProvider.notifier)
                        .stopListeningAndThink(_selectedEnergy);
                  },
                  onPressed: () {
                    // Fallback tap
                    if (voiceState == VoiceState.idle ||
                        voiceState == VoiceState.monitoring) {
                      ref
                          .read(voiceControllerProvider.notifier)
                          .startListening();
                    } else if (voiceState == VoiceState.listening) {
                      ref
                          .read(voiceControllerProvider.notifier)
                          .stopListeningAndThink(_selectedEnergy);
                    }
                  },
                ),

                const Gap(16),
                if (voiceState == VoiceState.listening)
                  TextButton(
                    onPressed: () =>
                        ref.read(voiceControllerProvider.notifier).cancel(),
                    child: const Text("Cancel"),
                  ),
              ],
            ),
          ),
      ],
    );
  }
}

class _SuggestionItem extends ConsumerWidget {
  final String text;
  final String energy;

  const _SuggestionItem({required this.text, required this.energy});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return GestureDetector(
      onTap: () {
        ref
            .read(voiceControllerProvider.notifier)
            .submitTextRequest(text, energy);
      },
      child: AyuelCard(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        backgroundColor: Colors.white.withOpacity(0.8),
        borderColor: AppTheme.primary.withOpacity(0.3),
        child: Row(
          children: [
            Icon(Icons.auto_awesome, size: 16, color: AppTheme.primary),
            const Gap(12),
            Expanded(
              child: Text(
                text,
                style: AppTheme.textTheme.bodyMedium?.copyWith(
                  color: AppTheme.primary,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
