/// Widget: Product Tabs Section
///
/// Tabbed content section with Description, Specifications, and Reviews tabs.
library;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.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/widgets/product_detail/write_review_button.dart';
import 'package:worker/features/reviews/domain/entities/review.dart';
import 'package:worker/features/reviews/presentation/providers/reviews_provider.dart';

/// Product Tabs Section
///
/// Displays tabbed content:
/// - Description: Rich text with features list
/// - Specifications: Table of product specs
/// - Reviews: Rating overview and review items
class ProductTabsSection extends StatefulWidget {

  const ProductTabsSection({super.key, required this.product});
  final Product product;

  @override
  State<ProductTabsSection> createState() => _ProductTabsSectionState();
}

class _ProductTabsSectionState extends State<ProductTabsSection>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    // Start with Specifications tab (index 0)
    _tabController = TabController(length: 2, vsync: this, initialIndex: 0);
    _tabController.addListener(() {
      setState(() {}); // Update IndexedStack when tab changes
    });
  }

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

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      color: colorScheme.surface,
      child: Column(
        children: [
          // Tab Navigation
          Container(
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(color: colorScheme.outlineVariant, width: 1),
              ),
            ),
            child: TabBar(
              controller: _tabController,
              labelColor: colorScheme.primary,
              unselectedLabelColor: colorScheme.onSurfaceVariant,
              labelStyle: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
              ),
              unselectedLabelStyle: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
              indicatorColor: colorScheme.primary,
              indicatorWeight: 2,
              tabs: const [
                Tab(text: 'Thông số'),
                Tab(text: 'Đánh giá'),
              ],
            ),
          ),

          // Tab Content (expands to fit content)
          IndexedStack(
            index: _tabController.index,
            children: [
              _SpecificationsTab(product: widget.product),
              _ReviewsTab(productId: widget.product.productId),
            ],
          ),
        ],
      ),
    );
  }
}

/// Description Tab Content
class _DescriptionTab extends StatelessWidget {

  const _DescriptionTab({required this.product});
  final Product product;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Main description
          Text(
            'Bộ sưu tập Cao cấp',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 12),

          Text(
            product.description ??
                'Sản phẩm gạch cao cấp với chất lượng vượt trội, mang đến vẻ đẹp tự nhiên và sang trọng cho không gian của bạn. Với bề mặt có texture tinh tế, sản phẩm tạo nên những đường vân tự nhiên chân thực.',
            style: TextStyle(
              fontSize: 14,
              height: 1.6,
              color: colorScheme.onSurface,
            ),
          ),

          const SizedBox(height: 20),

          // Features heading
          Text(
            'Đặc điểm nổi bật:',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 12),

          // Features list
          ...[
            'Bề mặt chống trầy xước cao',
            'Khả năng chống thấm nước tốt',
            'Màu sắc bền đẹp theo thời gian',
            'Dễ dàng vệ sinh và bảo trì',
            'Thân thiện với môi trường',
          ].map(
            (feature) => Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Icon(
                    FontAwesomeIcons.circleCheck,
                    size: 18,
                    color: AppColors.success,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      feature,
                      style: TextStyle(
                        fontSize: 14,
                        color: colorScheme.onSurface,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          const SizedBox(height: 20),

          // Application section
          Text(
            'Ứng dụng:',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 12),

          Text(
            'Phù hợp cho phòng khách, phòng ngủ, hành lang, văn phòng và các không gian thương mại. Đặc biệt phù hợp với phong cách nội thất hiện đại, tối giản và Scandinavian.',
            style: TextStyle(
              fontSize: 14,
              height: 1.6,
              color: colorScheme.onSurface,
            ),
          ),
        ],
      ),
    );
  }
}

/// Specifications Tab Content
class _SpecificationsTab extends StatelessWidget {

  const _SpecificationsTab({required this.product});
  final Product product;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    // Default specifications if not available
    final specs = product.specifications.isNotEmpty
        ? product.specifications
        : {
            'Kích thước': '60cm x 60cm',
            'Độ dày': '9.5mm',
            'Bề mặt': 'Matt (Nhám)',
            'Loại men': 'Granite kỹ thuật số',
            'Độ hấp thụ nước': '< 0.5%',
            'Độ chống mài mòn': 'PEI 4',
            'Chức năng': 'Lát nền, Ốp tường',
            'Xuất xứ': 'Việt Nam',
            'Bảo hành': '15 năm',
            'Tiêu chuẩn': 'TCVN 9081:2012, ISO 13006',
          };

    return Container(
      margin: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border.all(color: colorScheme.outlineVariant),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
          children: [
            Container(
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: colorScheme.outlineVariant),
                ),
              ),
              child: IntrinsicHeight(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // Label
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                        color: colorScheme.surface,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "Thương hiệu",
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                              color: colorScheme.onSurface,
                              height: 1.5,
                            ),
                          ),
                        ),
                      ),
                    ),

                    // Divider
                    Container(
                      width: 1,
                      color: colorScheme.outlineVariant,
                    ),

                    // Value
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                        child: Text(
                          '${product.brand}',
                          style: TextStyle(
                            fontSize: 14,
                            color: colorScheme.onSurface,
                            height: 1.5,
                          ),
                          softWrap: true,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: colorScheme.outlineVariant),
                ),
              ),
              child: IntrinsicHeight(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // Label
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                        color: colorScheme.surface,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "Dòng sản phẩm",
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                              color: colorScheme.onSurface,
                              height: 1.5,
                            ),
                          ),
                        ),
                      ),
                    ),

                    // Divider
                    Container(
                      width: 1,
                      color: colorScheme.outlineVariant,
                    ),

                    // Value
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                        child: Text(
                          '${product.itemGroupName}',
                          style: TextStyle(
                            fontSize: 14,
                            color: colorScheme.onSurface,
                            height: 1.5,
                          ),
                          softWrap: true,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            ...specs.entries.map((entry) {
              final isLast = entry == specs.entries.last;
              return Container(
                decoration: BoxDecoration(
                  border: isLast
                      ? null
                      : Border(
                    bottom: BorderSide(color: colorScheme.outlineVariant),
                  ),
                ),
                child: IntrinsicHeight(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // Label
                      Expanded(
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          color: colorScheme.surface,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              entry.key,
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                                color: colorScheme.onSurface,
                                height: 1.5,
                              ),
                            ),
                          ),
                        ),
                      ),

                      // Divider
                      Container(
                        width: 1,
                        color: colorScheme.outlineVariant,
                      ),

                      // Value
                      Expanded(
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          child: Text(
                            '${entry.value}',
                            style: TextStyle(
                              fontSize: 14,
                              color: colorScheme.onSurface,
                              height: 1.5,
                            ),
                            softWrap: true,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }),
          ],
      ),
    );
  }
}

/// Reviews Tab Content
class _ReviewsTab extends ConsumerWidget {

  const _ReviewsTab({required this.productId});
  final String productId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    final reviewsAsync = ref.watch(productReviewsProvider(productId));
    final avgRatingAsync = ref.watch(productAverageRatingProvider(productId));

    return Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Write Review Button
          WriteReviewButton(productId: productId),

          const SizedBox(height: 16),

          // Reviews Content
          reviewsAsync.when(
            data: (reviews) {
              if (reviews.isEmpty) {
                // Empty state
                return _buildEmptyState(colorScheme);
              }

              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Rating Overview
                  avgRatingAsync.when(
                    data: (avgRating) => _buildRatingOverview(colorScheme, reviews, avgRating),
                    loading: () => _buildRatingOverview(colorScheme, reviews, 0),
                    error: (_, __) => _buildRatingOverview(colorScheme, reviews, 0),
                  ),

                  const SizedBox(height: 24),

                  // Review Items
                  ...reviews.map((review) => _ReviewItem(review: review)),
                  const SizedBox(height: 24),

                ],
              );
            },
            loading: () => Center(
              child: Padding(
                padding: const EdgeInsets.all(40),
                child: const CustomLoadingIndicator(),
              ),
            ),
            error: (error, stack) => _buildErrorState(colorScheme, error.toString()),
          ),
        ],
      ),
    );
  }

  Widget _buildRatingOverview(ColorScheme colorScheme, List<Review> reviews, double avgRating) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0xFFF4F6F8),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          // Rating Score
          Text(
            avgRating.toStringAsFixed(2),
            style: TextStyle(
              fontSize: 36,
              fontWeight: FontWeight.w700,
              color: colorScheme.primary,
            ),
          ),

          const SizedBox(width: 16),

          // Rating Details
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Stars
              Row(
                children: List.generate(5, (index) {
                  if (index < avgRating.floor()) {
                    return const Icon(
                      FontAwesomeIcons.solidStar,
                      color: AppColors.warning,
                      size: 18,
                    );
                  } else if (index < avgRating) {
                    return const Icon(
                      FontAwesomeIcons.starHalfStroke,
                      color: AppColors.warning,
                      size: 18,
                    );
                  } else {
                    return const Icon(
                      FontAwesomeIcons.star,
                      color: AppColors.warning,
                      size: 18,
                    );
                  }
                }),
              ),

              const SizedBox(height: 4),

              // Review count
              Text(
                '${reviews.length} đánh giá',
                style: TextStyle(
                  fontSize: 14,
                  color: colorScheme.onSurfaceVariant,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState(ColorScheme colorScheme) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(40),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              FontAwesomeIcons.commentSlash,
              size: 48,
              color: colorScheme.onSurfaceVariant,
            ),
            const SizedBox(height: 16),
            Text(
              'Chưa có đánh giá nào',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: colorScheme.onSurface,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Hãy là người đầu tiên đánh giá sản phẩm này',
              style: TextStyle(
                fontSize: 14,
                color: colorScheme.onSurfaceVariant,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorState(ColorScheme colorScheme, String error) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(40),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              FontAwesomeIcons.circleExclamation,
              size: 48,
              color: AppColors.danger,
            ),
            const SizedBox(height: 16),
            Text(
              'Không thể tải đánh giá',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: colorScheme.onSurface,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              error.length > 100 ? '${error.substring(0, 100)}...' : error,
              style: TextStyle(
                fontSize: 13,
                color: colorScheme.onSurfaceVariant,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

/// Review Item Widget
class _ReviewItem extends StatelessWidget {

  const _ReviewItem({required this.review});
  final Review review;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      padding: const EdgeInsets.only(bottom: 16),
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: colorScheme.outlineVariant)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Reviewer Info
          Row(
            children: [
              // Avatar
              Container(
                width: 40,
                height: 40,
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Color(0xFFF4F6F8),
                ),
                child: Icon(
                  FontAwesomeIcons.solidUser,
                  color: colorScheme.onSurfaceVariant,
                  size: 20,
                ),
              ),

              const SizedBox(width: 12),

              // Name and Date
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      review.reviewerName ?? 'Người dùng',
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        color: colorScheme.onSurface,
                      ),
                    ),
                    if (review.reviewDate != null)
                      Text(
                        _formatDate(review.reviewDate!),
                        style: TextStyle(
                          fontSize: 12,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),

          const SizedBox(height: 8),

          // Rating Stars (convert from 0-1 to 5 stars)
          Row(
            children: List.generate(
              5,
              (index) => Icon(
                index < review.starsRating
                    ? FontAwesomeIcons.solidStar
                    : FontAwesomeIcons.star,
                color: AppColors.warning,
                size: 14,
              ),
            ),
          ),

          const SizedBox(height: 8),

          // Review Text
          Text(
            review.comment,
            style: TextStyle(
              fontSize: 14,
              height: 1.5,
              color: colorScheme.onSurface,
            ),
          ),
        ],
      ),
    );
  }

  /// Format review date for display
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final diff = now.difference(date);

    if (diff.inDays == 0) return 'Hôm nay';
    if (diff.inDays == 1) return 'Hôm qua';
    if (diff.inDays < 7) return '${diff.inDays} ngày trước';
    if (diff.inDays < 30) return '${(diff.inDays / 7).floor()} tuần trước';
    if (diff.inDays < 365) return '${(diff.inDays / 30).floor()} tháng trước';
    return '${(diff.inDays / 365).floor()} năm trước';
  }
}
