import 'package:english_learning/core/widgets/global_button.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/learning/modules/exercises/providers/exercise_provider.dart';
import 'package:english_learning/features/learning/modules/feedback/widgets/feedback_dialog.dart';
import 'package:english_learning/features/learning/modules/level/screens/level_list_screen.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class FeedbackScreen extends StatefulWidget {
  final String stdLearningId;
  final String topicId;
  final String topicTitle;

  const FeedbackScreen({
    super.key,
    required this.stdLearningId,
    required this.topicId,
    required this.topicTitle,
  });

  @override
  State<FeedbackScreen> createState() => _FeedbackScreenState();
}

class _FeedbackScreenState extends State<FeedbackScreen> {
  final FocusNode _focusNode = FocusNode();
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _controller.dispose();
    super.dispose();
  }

  void _unfocusTextField() {
    _focusNode.unfocus();
  }

  Future<void> _submitFeedback() async {
    if (_controller.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please enter your feedback before submitting.'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    final exerciseProvider =
        Provider.of<ExerciseProvider>(context, listen: false);

    try {
      final result = await exerciseProvider.submitFeedback(_controller.text);

      print('Feedback submitted successfully: $result');

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Feedback submitted successfully!'),
          backgroundColor: Colors.green,
        ),
      );

      // Show the dialog
      if (mounted) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext dialogContext) {
            return FeedbackDialog(
              onSubmit: () {
                Navigator.of(dialogContext).pop(); // Close the dialog
                Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(
                    builder: (context) => LevelListScreen(
                      topicId: widget.topicId,
                      topicTitle: widget.topicTitle,
                    ),
                  ),
                  (route) => false, // This removes all previous routes
                );
              },
            );
          },
        );
      }
    } catch (e) {
      print('Error submitting feedback: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to submit feedback: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _unfocusTextField,
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          automaticallyImplyLeading: false,
          iconTheme: const IconThemeData(color: AppColors.whiteColor),
          centerTitle: true,
          title: Text(
            'Feedback',
            style: AppTextStyles.whiteTextStyle.copyWith(
              fontSize: 16,
              fontWeight: FontWeight.w900,
            ),
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: AppColors.gradientTheme,
            ),
          ),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Column(
            children: [
              const SizedBox(height: 24),
              Text(
                'Is there anything you would like to share after completing this exercise?',
                style: AppTextStyles.blackTextStyle.copyWith(
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 16),
              AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: _focusNode.hasFocus
                          ? AppColors.blueColor.withOpacity(0.3)
                          : Colors.transparent,
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: TextField(
                  controller: _controller,
                  focusNode: _focusNode,
                  maxLines: 8,
                  style: AppTextStyles.blackTextStyle.copyWith(
                    fontSize: 14,
                  ),
                  cursorColor: AppColors.blackColor,
                  decoration: InputDecoration(
                    hintText: 'Type your message here',
                    hintStyle:
                        AppTextStyles.greyTextStyle.copyWith(fontSize: 14),
                    filled: true,
                    fillColor: _focusNode.hasFocus
                        ? AppColors.whiteColor
                        : AppColors.whiteColor,
                    contentPadding: const EdgeInsets.all(16),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide.none,
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(
                        color: AppColors.blueColor,
                        width: 2,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide(
                          color: AppColors.disableColor.withOpacity(0.5)),
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 24),
              GlobalButton(
                text: 'Send',
                onPressed: _submitFeedback,
              ),
              const SizedBox(height: 16),
              GlobalButton(
                text: 'Skip',
                textColor: AppColors.blueColor,
                backgroundColor: Colors.transparent,
                borderColor: AppColors.blueColor,
                onPressed: () {
                  Navigator.pushAndRemoveUntil(
                      context,
                      MaterialPageRoute(
                        builder: (context) => LevelListScreen(
                          topicId: widget.topicId,
                          topicTitle: widget.topicTitle,
                        ),
                      ),
                      (Route<dynamic> route) => route.isFirst);
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}
