import 'package:english_learning/core/widgets/custom_snackbar.dart';
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();
  bool _isLoading = false;

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

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

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

  Future<void> _navigateToLevelList() async {
    if (!mounted) return;

    await Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(
        builder: (context) => LevelListScreen(
          topicId: widget.topicId,
          topicTitle: widget.topicTitle,
        ),
      ),
      (Route<dynamic> route) => route.isFirst,
    );
  }

  Future<void> _submitFeedback() async {
    _unfocusTextField();

    if (_controller.text.trim().isEmpty) {
      CustomSnackBar.show(
        context,
        message: 'Please enter your feedback before submitting.',
        isError: true,
      );

      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final exerciseProvider =
          Provider.of<ExerciseProvider>(context, listen: false);
      final result =
          await exerciseProvider.submitFeedback(_controller.text.trim());

      if (!mounted) return;

      setState(() {
        _isLoading = false;
      });

      if (result != null) {
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext dialogContext) => PopScope(
            canPop: false,
            child: FeedbackDialog(
              onSubmit: () {
                Navigator.pop(dialogContext);
                _navigateToLevelList();
              },
            ),
          ),
        );
      } else {
        CustomSnackBar.show(
          context,
          message: 'Failed to submit feedback. Please try again.',
          isError: true,
        );
      }
    } catch (e) {
      if (!mounted) return;

      setState(() {
        _isLoading = false;
      });

      CustomSnackBar.show(
        context,
        message: 'An error occurred: ${e.toString()}',
        isError: true,
      );
    }
  }

  @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: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              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.2)
                            : 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: 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: const BorderSide(
                          color: AppColors.disableColor,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                GlobalButton(
                  text: 'Send',
                  isLoading: _isLoading,
                  onPressed: _isLoading ? null : _submitFeedback,
                ),
                const SizedBox(height: 16),
                GlobalButton(
                  text: 'Skip',
                  textColor: AppColors.blueColor,
                  backgroundColor: Colors.transparent,
                  borderColor: AppColors.blueColor,
                  onPressed: _isLoading ? null : _navigateToLevelList,
                ),
                const SizedBox(height: 24),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
