import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../application/analytic/product_analytic_loader/product_analytic_loader_bloc.dart';
import '../../../../common/extension/extension.dart';
import '../../../../common/theme/theme.dart';
import '../../../../domain/analytic/analytic.dart';
import '../../../../injection.dart';
import '../../../components/appbar/appbar.dart';
import '../../../components/field/date_range_picker_field.dart';

@RoutePage()
class ProductAnalyticPage extends StatefulWidget implements AutoRouteWrapper {
  const ProductAnalyticPage({super.key});

  @override
  State<ProductAnalyticPage> createState() => _ProductAnalyticPageState();

  @override
  Widget wrappedRoute(BuildContext context) => BlocProvider(
    create: (context) =>
        getIt<ProductAnalyticLoaderBloc>()
          ..add(ProductAnalyticLoaderEvent.fetched()),
    child: this,
  );
}

class _ProductAnalyticPageState extends State<ProductAnalyticPage>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late AnimationController _cardAnimationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

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

  void _initializeAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    _cardAnimationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
      ),
    );

    _slideAnimation =
        Tween<Offset>(begin: const Offset(0, 0.3), end: Offset.zero).animate(
          CurvedAnimation(
            parent: _animationController,
            curve: const Interval(0.2, 1.0, curve: Curves.easeOutCubic),
          ),
        );

    _animationController.forward();
    _cardAnimationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _cardAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.background,
      body: BlocListener<ProductAnalyticLoaderBloc, ProductAnalyticLoaderState>(
        listenWhen: (previous, current) =>
            previous.dateFrom != current.dateFrom ||
            previous.dateTo != current.dateTo,
        listener: (context, state) {
          context.read<ProductAnalyticLoaderBloc>().add(
            ProductAnalyticLoaderEvent.fetched(),
          );
        },
        child:
            BlocBuilder<ProductAnalyticLoaderBloc, ProductAnalyticLoaderState>(
              builder: (context, state) {
                return CustomScrollView(
                  physics: const BouncingScrollPhysics(),
                  slivers: [
                    _buildSliverAppBar(),
                    SliverToBoxAdapter(
                      child: SlideTransition(
                        position: _slideAnimation,
                        child: FadeTransition(
                          opacity: _fadeAnimation,
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: DateRangePickerField(
                              maxDate: DateTime.now(),
                              startDate: state.dateFrom,
                              endDate: state.dateTo,
                              onChanged: (startDate, endDate) {
                                context.read<ProductAnalyticLoaderBloc>().add(
                                  ProductAnalyticLoaderEvent.rangeDateChanged(
                                    startDate!,
                                    endDate!,
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                      ),
                    ),
                    _buildSummarySection(state.productAnalytic),
                    _buildProductsList(state.productAnalytic),
                  ],
                );
              },
            ),
      ),
    );
  }

  // SLIVER APP BAR
  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 120,
      floating: false,
      pinned: true,
      elevation: 0,
      backgroundColor: AppColor.primary,
      flexibleSpace: CustomAppBar(title: context.lang.product_analytic),
    );
  }

  // SUMMARY SECTION
  Widget _buildSummarySection(ProductAnalytic productAnalytic) {
    return SliverToBoxAdapter(
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: SlideTransition(
          position: _slideAnimation,
          child: Container(
            margin: const EdgeInsets.all(16),
            child: _buildSummaryCards(productAnalytic.data),
          ),
        ),
      ),
    );
  }

  // PRODUCTS LIST
  Widget _buildProductsList(ProductAnalytic productAnalytic) {
    return SliverPadding(
      padding: const EdgeInsets.all(16),
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
          return AnimatedBuilder(
            animation: _cardAnimationController,
            builder: (context, child) {
              final delay = index * 0.1;
              final progress = (_cardAnimationController.value - delay).clamp(
                0.0,
                1.0,
              );
              final animValue = Curves.easeOutCubic
                  .transform(progress)
                  .clamp(0.0, 1.0);

              return Transform.translate(
                offset: Offset(0, 50 * (1 - animValue)),
                child: Opacity(
                  opacity: animValue,
                  child: _buildProductCard(
                    productAnalytic,
                    productAnalytic.data[index],
                    index,
                  ),
                ),
              );
            },
          );
        }, childCount: productAnalytic.data.length),
      ),
    );
  }

  // SUMMARY CARDS
  Widget _buildSummaryCards(List<ProductAnalyticData> data) {
    final stats = _calculateSummaryStats(data);

    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: _buildSummaryCard(
                icon: Icons.monetization_on,
                title: context.lang.total_revenue,
                value: _formatCurrency(stats.totalRevenue),
                color: AppColor.success,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildSummaryCard(
                icon: Icons.shopping_cart,
                title: context.lang.total_sold,
                value: _formatNumber(stats.totalQuantity),
                color: AppColor.info,
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _buildSummaryCard(
                icon: Icons.receipt_long,
                title: context.lang.total_orders,
                value: _formatNumber(stats.totalOrders),
                color: AppColor.warning,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildSummaryCard(
                icon: Icons.trending_up,
                title: context.lang.average_price,
                value: _formatCurrency(stats.averageOrderValue),
                color: AppColor.primary,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildSummaryCard({
    required IconData icon,
    required String title,
    required String value,
    required Color color,
  }) {
    return TweenAnimationBuilder<double>(
      tween: Tween<double>(begin: 0.0, end: 1.0),
      duration: const Duration(milliseconds: 800),
      curve: Curves.elasticOut,
      builder: (context, animationValue, child) {
        return Transform.scale(
          scale: animationValue,
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: AppColor.surface,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: color.withOpacity(0.1),
                  blurRadius: 15,
                  offset: const Offset(0, 5),
                ),
              ],
              border: Border.all(color: color.withOpacity(0.2), width: 1.5),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [color.withOpacity(0.2), color.withOpacity(0.1)],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(icon, color: color, size: 24),
                ),
                const SizedBox(height: 16),
                Text(
                  title,
                  style: _getTextStyle(
                    AppStyle.md,
                    color: AppColor.textSecondary,
                    weight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  value,
                  style: _getTextStyle(
                    AppStyle.xxl,
                    color: color,
                    weight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // PRODUCT CARD - NEW CLEAN LAYOUT
  Widget _buildProductCard(
    ProductAnalytic productAnalytic,
    ProductAnalyticData product,
    int index,
  ) {
    return TweenAnimationBuilder<double>(
      tween: Tween<double>(begin: 0.0, end: 1.0),
      duration: Duration(milliseconds: 600 + (index * 100)),
      curve: Curves.easeOutBack,
      builder: (context, animationValue, child) {
        final clampedValue = animationValue.clamp(0.0, 1.0);

        return Transform.translate(
          offset: Offset(0, 30 * (1 - clampedValue)),
          child: Opacity(
            opacity: clampedValue,
            child: Container(
              margin: EdgeInsets.only(
                bottom: index == productAnalytic.data.length - 1 ? 0 : 16,
              ),
              child: _buildCardContent(productAnalytic, product, index),
            ),
          ),
        );
      },
    );
  }

  Widget _buildCardContent(
    ProductAnalytic productAnalytic,
    ProductAnalyticData product,
    int index,
  ) {
    return Container(
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(8),
          bottomRight: Radius.circular(8),
        ),
        boxShadow: [
          BoxShadow(
            color: _getCategoryColor(product.categoryName).withOpacity(0.08),
            blurRadius: 24,
            offset: const Offset(0, 12),
          ),
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(8),
          onTap: () => _onProductTap(product),
          child: Column(
            children: [
              _buildCardHeader(product, index),
              _buildCardBody(productAnalytic, product),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCardHeader(ProductAnalyticData product, int index) {
    return Container(
      width: double.infinity,
      height: 4,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            _getCategoryColor(product.categoryName),
            _getCategoryColor(product.categoryName).withOpacity(0.6),
          ],
        ),
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(8),
          topRight: Radius.circular(8),
        ),
      ),
    );
  }

  Widget _buildCardBody(
    ProductAnalytic productAnalytic,
    ProductAnalyticData product,
  ) {
    final index = productAnalytic.data.indexOf(product);

    return Padding(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildProductHeader(product, index),
          const SizedBox(height: 20),
          _buildStatsSection(product),
          const SizedBox(height: 16),
          _buildAveragePriceSection(product),
        ],
      ),
    );
  }

  Widget _buildProductHeader(ProductAnalyticData product, int index) {
    return Row(
      children: [
        _buildCategoryIcon(product.categoryName),
        const SizedBox(width: 16),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                product.productName,
                style: _getTextStyle(AppStyle.lg, weight: FontWeight.bold),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 4),
              Text(
                product.categoryName,
                style: _getTextStyle(
                  AppStyle.sm,
                  color: _getCategoryColor(product.categoryName),
                  weight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
        _buildRankingBadge(index),
      ],
    );
  }

  Widget _buildCategoryIcon(String categoryName) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            _getCategoryColor(categoryName).withOpacity(0.1),
            _getCategoryColor(categoryName).withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: _getCategoryColor(categoryName).withOpacity(0.2),
          width: 1.5,
        ),
      ),
      child: Icon(
        _getCategoryIcon(categoryName),
        color: _getCategoryColor(categoryName),
        size: 28,
      ),
    );
  }

  Widget _buildRankingBadge(int index) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: _getRankingColor(index),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Text(
        '#${index + 1}',
        style: _getTextStyle(
          AppStyle.xs,
          color: AppColor.white,
          weight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildStatsSection(ProductAnalyticData product) {
    return Row(
      children: [
        Expanded(flex: 3, child: _buildRevenueCard(product)),
        const SizedBox(width: 12),
        Expanded(flex: 2, child: _buildSecondaryStats(product)),
      ],
    );
  }

  Widget _buildRevenueCard(ProductAnalyticData product) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColor.success.withOpacity(0.1),
            AppColor.success.withOpacity(0.05),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColor.success.withOpacity(0.2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.trending_up, color: AppColor.success, size: 20),
              const SizedBox(width: 8),
              Text(
                context.lang.revenue,
                style: _getTextStyle(
                  AppStyle.sm,
                  color: AppColor.success,
                  weight: FontWeight.w600,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            product.revenue.currencyFormatRp,
            style: _getTextStyle(
              AppStyle.xl,
              color: AppColor.success,
              weight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSecondaryStats(ProductAnalyticData product) {
    return Column(
      children: [
        _buildStatCard(
          icon: Icons.shopping_cart_outlined,
          value: '${product.quantitySold}',
          label: context.lang.sold,
          color: AppColor.info,
        ),
        const SizedBox(height: 8),
        _buildStatCard(
          icon: Icons.receipt_outlined,
          value: '${product.orderCount}',
          label: context.lang.orders,
          color: AppColor.warning,
        ),
      ],
    );
  }

  Widget _buildStatCard({
    required IconData icon,
    required String value,
    required String label,
    required Color color,
  }) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColor.background.withOpacity(0.5),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColor.border.withOpacity(0.1)),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(icon, color: color, size: 16),
              const SizedBox(width: 4),
              Text(
                value,
                style: _getTextStyle(
                  AppStyle.md,
                  color: color,
                  weight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 2),
          Text(
            label,
            style: _getTextStyle(
              AppStyle.xs,
              color: AppColor.textSecondary,
              weight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAveragePriceSection(ProductAnalyticData product) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            _getCategoryColor(product.categoryName).withOpacity(0.05),
            _getCategoryColor(product.categoryName).withOpacity(0.02),
          ],
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            context.lang.average_price,
            style: _getTextStyle(
              AppStyle.sm,
              color: AppColor.textSecondary,
              weight: FontWeight.w500,
            ),
          ),
          Text(
            product.averagePrice.round().currencyFormatRp,
            style: _getTextStyle(
              AppStyle.sm,
              color: _getCategoryColor(product.categoryName),
              weight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  // HELPER METHODS
  SummaryStats _calculateSummaryStats(List<ProductAnalyticData> data) {
    final totalRevenue = data.fold<double>(
      0,
      (sum, item) => sum + item.revenue,
    );
    final totalQuantity = data.fold<int>(
      0,
      (sum, item) => sum + item.quantitySold,
    );
    final totalOrders = data.fold<int>(0, (sum, item) => sum + item.orderCount);
    final averageOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0;

    return SummaryStats(
      totalRevenue: totalRevenue,
      totalQuantity: totalQuantity,
      totalOrders: totalOrders,
      averageOrderValue: averageOrderValue.roundToDouble(),
    );
  }

  TextStyle _getTextStyle(
    TextStyle? baseStyle, {
    Color? color,
    FontWeight? weight,
  }) {
    return baseStyle?.copyWith(color: color, fontWeight: weight) ??
        TextStyle(color: color, fontWeight: weight);
  }

  void _onProductTap(ProductAnalyticData product) {
    // Handle product detail navigation
  }

  Color _getCategoryColor(String categoryName) {
    switch (categoryName) {
      case 'Makanan Utama':
        return AppColor.primary;
      case 'Minuman':
        return AppColor.info;
      case 'Snack':
        return AppColor.warning;
      default:
        return AppColor.secondary;
    }
  }

  Color _getRankingColor(int index) {
    switch (index) {
      case 0:
        return const Color(0xFFFFD700); // Gold
      case 1:
        return const Color(0xFFC0C0C0); // Silver
      case 2:
        return const Color(0xFFCD7F32); // Bronze
      default:
        return AppColor.primary;
    }
  }

  IconData _getCategoryIcon(String categoryName) {
    switch (categoryName) {
      case 'Makanan Utama':
        return Icons.restaurant;
      case 'Minuman':
        return Icons.local_cafe;
      case 'Snack':
        return Icons.fastfood;
      default:
        return Icons.category;
    }
  }

  String _formatCurrency(double amount) {
    if (amount >= 1000000) {
      return 'Rp ${(amount / 1000000).toStringAsFixed(1)}jt';
    } else if (amount >= 1000) {
      return 'Rp ${(amount / 1000).toStringAsFixed(0)}rb';
    } else {
      return 'Rp ${amount.toStringAsFixed(0)}';
    }
  }

  String _formatNumber(int number) {
    if (number >= 1000) {
      return '${(number / 1000).toStringAsFixed(1)}k';
    }
    return number.toString();
  }
}

// HELPER CLASS
class SummaryStats {
  final double totalRevenue;
  final int totalQuantity;
  final int totalOrders;
  final double averageOrderValue;

  SummaryStats({
    required this.totalRevenue,
    required this.totalQuantity,
    required this.totalOrders,
    required this.averageOrderValue,
  });
}
