import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;

// Adjust these import paths to match your project structure.
import '../../../../constants/color_constants.dart';
import '../../../../widgets/text_widget.dart';
import 'ai_processing_screen.dart';

// TODO: replace with your actual search/results screen import + widget.
// import '../search/search_result_screen.dart';

class VoiceAssistantScreen extends StatefulWidget {
  const VoiceAssistantScreen({super.key});

  @override
  State<VoiceAssistantScreen> createState() => _VoiceAssistantScreenState();
}

class _VoiceAssistantScreenState extends State<VoiceAssistantScreen>
    with SingleTickerProviderStateMixin {
  final stt.SpeechToText _speech = stt.SpeechToText();

  bool _speechAvailable = false;
  bool isListening = true;
  String recognizedText = "Tap the mic and start speaking";

  late final AnimationController controller;

  @override
  void initState() {
    super.initState();

    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);

    _initSpeech();
  }

  @override
  void dispose() {
    controller.dispose();
    _speech.stop();
    super.dispose();
  }

  // ---------------- SPEECH SETUP ----------------

  Future<void> _initSpeech() async {
    _speechAvailable = await _speech.initialize(
      onStatus: (status) {
        // Fires when recognition stops on its own (silence / done)
        if (status == 'notListening' || status == 'done') {
          if (isListening) {
            setState(() => isListening = false);
            _handleFinalResult();
          }
        }
      },
      onError: (error) {
        setState(() => isListening = false);
      },
    );
    setState(() {});
  }

  Future<void> _toggleListening() async {
    if (!_speechAvailable) return;

    if (isListening) {
      await _speech.stop();
      setState(() => isListening = false);
      _handleFinalResult();
      return;
    }

    setState(() {
      isListening = true;
      recognizedText = "Listening...";
    });

    await _speech.listen(
      onResult: (result) {
        setState(() {
          recognizedText = result.recognizedWords;
        });
      },
    );
  }

  /// Called once listening stops (either the user tapped stop, or the
  /// recognizer auto-stopped after silence). Navigates forward with
  /// whatever was captured, as long as it isn't empty.
  void _handleFinalResult() {
    final query = recognizedText.trim();

    final isPlaceholder = query.isEmpty ||
        query == "Listening..." ||
        query == "Tap the mic and start speaking";

    if (isPlaceholder) return;

    // TODO: swap this for your real navigation, e.g.:
    // Navigator.pushReplacement(
    //   context,
    //   MaterialPageRoute(
    //     builder: (_) => SearchResultScreen(query: query),
    //   ),
    // );
    //
    // If this screen was opened for a result (e.g. from a search bar),
    // you can instead just pop with the value:
    // Navigator.pop(context, query);

    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (_) => AIAssistantScreen(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorConstants.secondaryColor,
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _buildHeader(context),
            const SizedBox(height: 4),
            _buildStatusChip(),
            const SizedBox(height: 26),
            _buildMicStage(),
            const SizedBox(height: 26),

            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32),
              child: ReusableTextWidget(
                text: recognizedText,
                fontSize: 16,
                fontWeight: FontWeight.w600,
                textAlign: TextAlign.center,
                color: ColorConstants.blackColor,
              ),
            ),

            _buildPremiumMicButton(),
            const SizedBox(height: 22),
          ],
        ),
      ),
    );
  }

  // ---------------- HEADER ----------------

  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(18, 14, 18, 0),
      child: Row(
        children: [
          InkWell(
            onTap: () => Navigator.maybePop(context),
            borderRadius: BorderRadius.circular(30),
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: ColorConstants.lightGreyBg,
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.arrow_back_ios_new_rounded,
                size: 16,
                color: ColorConstants.darkGreyColor,
              ),
            ),
          ),
          const Expanded(
            child: Center(
              child: ReusableTextWidget(
                text: "Voice Assistant",
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: ColorConstants.blackColor,
              ),
            ),
          ),
          const SizedBox(width: 40),
        ],
      ),
    );
  }

  Widget _buildStatusChip() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
      decoration: BoxDecoration(
        color: ColorConstants.primaryColor1,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            height: 8,
            width: 8,
            decoration: const BoxDecoration(
              color: ColorConstants.primaryColor,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 8),
          ReusableTextWidget(
            text: isListening ? "Listening" : "Paused",
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: ColorConstants.primaryColor,
          ),
        ],
      ),
    );
  }

  // ---------------- MIC / LOTTIE ----------------

  Widget _buildMicStage() {
    return SizedBox(
      height: 270,
      width: 270,
      child: Center(
        child: Lottie.asset(
          "assets/lotties/ai.json",
          height: 250,
          width: 250,
          repeat: true,
          animate: isListening,
        ),
      ),
    );
  }

  // ---------------- PREMIUM MIC BUTTON ----------------

  Widget _buildPremiumMicButton() {
    return Column(
      children: [
        GestureDetector(
          onTap: _toggleListening,
          child: AnimatedBuilder(
            animation: controller,
            builder: (context, child) {
              final ringOpacity =
              isListening ? 0.18 + (controller.value * 0.18) : 0.0;
              return Container(
                height: 92,
                width: 92,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color:
                  ColorConstants.primaryColor1.withOpacity(ringOpacity),
                ),
                child: Center(child: child),
              );
            },
            child: Container(
              height: 68,
              width: 68,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [ColorConstants.primaryColor, Color(0xFF8C3EAE)],
                ),
                boxShadow: [
                  BoxShadow(
                    color: ColorConstants.primaryColor.withOpacity(0.4),
                    blurRadius: 20,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
              child: Icon(
                isListening ? Icons.mic_rounded : Icons.mic_off_rounded,
                color: ColorConstants.secondaryColor,
                size: 28,
              ),
            ),
          ),
        ),
        const SizedBox(height: 12),
        ReusableTextWidget(
          text: !_speechAvailable
              ? "Speech recognition unavailable"
              : isListening
              ? "Tap to stop listening"
              : "Tap to speak",
          fontSize: 13,
          fontWeight: FontWeight.w500,
          color: ColorConstants.lightGrey,
        ),
      ],
    );
  }
}

/// Temporary placeholder so the file compiles and navigation is visible.
/// Delete this and point `_handleFinalResult` at your real screen.
class _PlaceholderResultScreen extends StatelessWidget {
  final String query;

  const _PlaceholderResultScreen({required this.query});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Search Results")),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Text(
            'You said: "$query"\n\nReplace _PlaceholderResultScreen with your real search/results page.',
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 16),
          ),
        ),
      ),
    );
  }
}