/// Page: Write Review
///
/// Form page for users to write product reviews with star rating.
library;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/products/domain/entities/product.dart';
import 'package:worker/features/products/presentation/providers/products_provider.dart';
import 'package:worker/features/products/presentation/widgets/write_review/review_guidelines_card.dart';
import 'package:worker/features/products/presentation/widgets/write_review/star_rating_selector.dart';
import 'package:worker/features/reviews/presentation/providers/reviews_provider.dart';

/// Write Review Page
///
/// Allows users to write a review for a product:
/// - Product info card (read-only)
/// - Star rating selector (1-5, required)
/// - Review content (textarea, min 20 chars, max 1000)
/// - Character counter (red if < 20)
/// - Review guidelines
/// - Submit button with loading state
class WriteReviewPage extends ConsumerStatefulWidget {
  /// Product ID to review
  final String productId;

  const WriteReviewPage({super.key, required this.productId});

  @override
  ConsumerState<WriteReviewPage> createState() => _WriteReviewPageState();
}

class _WriteReviewPageState extends ConsumerState<WriteReviewPage> {
  // Form state
  int _selectedRating = 0;
  final _contentController = TextEditingController();
  bool _isSubmitting = false;

  // Validation errors
  String? _ratingError;
  String? _contentError;

  // Constants
  static const int _minContentLength = 20;
  static const int _maxContentLength = 1000;

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  /// Validate form fields
  bool _validateForm() {
    bool isValid = true;

    // Reset errors
    setState(() {
      _ratingError = null;
      _contentError = null;
    });

    // Rating validation
    if (_selectedRating == 0) {
      setState(() => _ratingError = 'Vui lòng chọn số sao đánh giá');
      isValid = false;
    }

    // Content validation
    final content = _contentController.text.trim();
    if (content.length < _minContentLength) {
      setState(() =>
          _contentError = 'Nội dung đánh giá phải có ít nhất $_minContentLength ký tự');
      isValid = false;
    }

    return isValid;
  }

  /// Submit review
  Future<void> _submitReview() async {
    if (!_validateForm()) return;

    setState(() => _isSubmitting = true);

    try {
      final submitUseCase = await ref.read(submitReviewProvider.future);

      // API expects rating on 0-5 scale directly
      // User selected 1-5 stars, pass as-is
      final apiRating = _selectedRating.toDouble();

      await submitUseCase(
        itemId: widget.productId,
        rating: apiRating,
        comment: _contentController.text.trim(),
      );

      if (mounted) {
        final colorScheme = Theme.of(context).colorScheme;

        // Show success message
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(FontAwesomeIcons.circleCheck, color: colorScheme.onPrimary),
                const SizedBox(width: 12),
                const Expanded(
                  child: Text('Đánh giá của bạn đã được gửi thành công!'),
                ),
              ],
            ),
            backgroundColor: AppColors.success,
            behavior: SnackBarBehavior.floating,
          ),
        );

        // Invalidate reviews to refresh the list
        ref.invalidate(productReviewsProvider(widget.productId));

        // Navigate back
        context.pop();
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isSubmitting = false);
        final colorScheme = Theme.of(context).colorScheme;

        // Show error message
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(
                  FontAwesomeIcons.triangleExclamation,
                  color: colorScheme.onPrimary,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text('Lỗi: ${e.toString()}'),
                ),
              ],
            ),
            backgroundColor: AppColors.danger,
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final productAsync = ref.watch(productDetailProvider(productId: widget.productId));

    return Scaffold(
      backgroundColor: colorScheme.surface,
      // Standard AppBar
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: AppBarSpecs.elevation,
        centerTitle: false,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: colorScheme.onSurface,
          ),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Viết đánh giá sản phẩm',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),

      body: productAsync.when(
        data: (product) => _buildForm(product),
        loading: () => const CustomLoadingIndicator(),
        error: (error, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                FontAwesomeIcons.circleExclamation,
                size: 48,
                color: colorScheme.error,
              ),
              const SizedBox(height: 16),
              Text(
                'Không thể tải thông tin sản phẩm',
                style: TextStyle(
                  fontSize: 16,
                  color: colorScheme.onSurface,
                ),
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: () => context.pop(),
                child: const Text('Quay lại'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildForm(Product product) {
    final colorScheme = Theme.of(context).colorScheme;

    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Product Info Card (Read-only)
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: colorScheme.surface,
                border: Border.all(color: colorScheme.outlineVariant, width: 2),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                children: [
                  // Product Image
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: CachedNetworkImage(
                      imageUrl: product.images.isNotEmpty
                          ? product.images.first
                          : '',
                      width: 80,
                      height: 80,
                      fit: BoxFit.cover,
                      placeholder: (context, url) => Container(
                        width: 80,
                        height: 80,
                        color: colorScheme.surfaceContainerLowest,
                        child: Center(
                          child: CustomLoadingIndicator(color: colorScheme.primary, size: 20),
                        ),
                      ),
                      errorWidget: (context, url, error) => Container(
                        width: 80,
                        height: 80,
                        color: colorScheme.surfaceContainerLowest,
                        child: Icon(
                          FontAwesomeIcons.image,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(width: 16),

                  // Product Info
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          product.name,
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: colorScheme.onSurface,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 6),
                        Text(
                          'Mã: ${product.productId}',
                          style: TextStyle(
                            fontSize: 13,
                            color: colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 28),

            // Rating Section (Required)
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                RichText(
                  text: TextSpan(
                    text: 'Xếp hạng của bạn',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                    children: [
                      TextSpan(
                        text: ' *',
                        style: TextStyle(color: colorScheme.error),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Bấm vào ngôi sao để chọn đánh giá',
                  style: TextStyle(
                    fontSize: 14,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
                const SizedBox(height: 16),

                // Star Rating Selector
                StarRatingSelector(
                  rating: _selectedRating,
                  onRatingChanged: (rating) {
                    setState(() {
                      _selectedRating = rating;
                      _ratingError = null;
                    });
                  },
                ),

                // Rating Error
                if (_ratingError != null) ...[
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Icon(
                        FontAwesomeIcons.triangleExclamation,
                        size: 14,
                        color: colorScheme.error,
                      ),
                      const SizedBox(width: 6),
                      Text(
                        _ratingError!,
                        style: TextStyle(
                          fontSize: 13,
                          color: colorScheme.error,
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),

            const SizedBox(height: 28),

            // Review Content (Required)
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                RichText(
                  text: TextSpan(
                    text: 'Nội dung đánh giá',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                    children: [
                      TextSpan(
                        text: ' *',
                        style: TextStyle(color: colorScheme.error),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 8),

                // Textarea
                TextField(
                  controller: _contentController,
                  maxLines: 6,
                  maxLength: _maxContentLength,
                  decoration: InputDecoration(
                    hintText:
                        'Chia sẻ trải nghiệm của bạn về sản phẩm này...',
                    hintStyle: TextStyle(
                      fontSize: 15,
                      color: colorScheme.onSurfaceVariant,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: colorScheme.outlineVariant,
                        width: 2,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: colorScheme.outlineVariant,
                        width: 2,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: colorScheme.primary,
                        width: 2,
                      ),
                    ),
                    contentPadding: const EdgeInsets.all(14),
                    counterText: '', // Hide default counter
                  ),
                  style: TextStyle(
                    fontSize: 15,
                    height: 1.6,
                    color: colorScheme.onSurface,
                  ),
                  onChanged: (value) {
                    setState(() {
                      _contentError = null;
                    });
                  },
                ),

                const SizedBox(height: 6),

                // Character Counter
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      '${_contentController.text.length}',
                      style: TextStyle(
                        fontSize: 13,
                        color: _contentController.text.length < _minContentLength
                            ? colorScheme.error
                            : colorScheme.onSurfaceVariant,
                      ),
                    ),
                    Text(
                      ' / $_maxContentLength ký tự',
                      style: TextStyle(
                        fontSize: 13,
                        color: colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ],
                ),

                // Content Error
                if (_contentError != null) ...[
                  const SizedBox(height: 6),
                  Row(
                    children: [
                      Icon(
                        FontAwesomeIcons.triangleExclamation,
                        size: 14,
                        color: colorScheme.error,
                      ),
                      const SizedBox(width: 6),
                      Expanded(
                        child: Text(
                          _contentError!,
                          style: TextStyle(
                            fontSize: 13,
                            color: colorScheme.error,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),

            const SizedBox(height: 24),

            // Guidelines
            const ReviewGuidelinesCard(),

            const SizedBox(height: 24),

            // Submit Button
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isSubmitting ? null : _submitReview,
                style: ElevatedButton.styleFrom(
                  backgroundColor: colorScheme.primary,
                  disabledBackgroundColor: colorScheme.outlineVariant,
                  foregroundColor: colorScheme.onPrimary,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  elevation: 0,
                ),
                child: _isSubmitting
                    ? CustomLoadingIndicator(color: colorScheme.onPrimary, size: 20)
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            FontAwesomeIcons.paperPlane,
                            size: 16,
                            color: colorScheme.onPrimary,
                          ),
                          const SizedBox(width: 10),
                          Text(
                            'Gửi đánh giá',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: colorScheme.onPrimary,
                            ),
                          ),
                        ],
                      ),
              ),
            ),

            const SizedBox(height: 24),
          ],
        ),
      ),
    );
  }
}
