import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';

import '../../../../common/extension/extension.dart';
import '../../../../common/theme/theme.dart';
import '../../../../domain/analytic/analytic.dart';
import '../../../components/spacer/spacer.dart';
import 'product_detail_bottom_sheet.dart';

class SalesTopProductsCard extends StatelessWidget {
  final ProductAnalytic productAnalytic;
  final bool isFetching;

  const SalesTopProductsCard({
    super.key,
    required this.productAnalytic,
    required this.isFetching,
  });

  @override
  Widget build(BuildContext context) {
    if (isFetching) return _buildShimmer();

    final data = productAnalytic.data;

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Title row
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                context.lang.best_selling_products,
                style: AppStyle.xl.copyWith(
                  fontWeight: FontWeight.bold,
                  color: AppColor.textPrimary,
                  fontSize: 18,
                ),
              ),
              Text(
                '${data.length} ${context.lang.product.toLowerCase()}',
                style: AppStyle.sm.copyWith(
                  color: AppColor.textSecondary,
                  fontWeight: FontWeight.w500,
                  fontSize: 13,
                ),
              ),
            ],
          ),
          const SpaceHeight(16),

          // Product list
          if (data.isEmpty)
            Center(
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 20),
                child: Text(
                  context.lang.no_data_available,
                  style: AppStyle.md.copyWith(color: AppColor.textSecondary),
                ),
              ),
            )
          else
            ...data.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              return Column(
                children: [
                  _buildProductItem(context, item, index + 1),
                  if (index < data.length - 1)
                    const Divider(height: 1, thickness: 0.5),
                ],
              );
            }),
        ],
      ),
    );
  }

  Widget _buildProductItem(
    BuildContext context,
    ProductAnalyticData item,
    int rank,
  ) {
    final isTopThree = rank <= 3;
    final totalRevenue = productAnalytic.data.fold<int>(
      0,
      (sum, e) => sum + e.revenue,
    );

    return GestureDetector(
      onTap: () => ProductDetailBottomSheet.show(
        context: context,
        product: item,
        totalRevenue: totalRevenue,
      ),
      behavior: HitTestBehavior.opaque,
      child: _buildProductItemContent(context, item, rank, isTopThree),
    );
  }

  Widget _buildProductItemContent(
    BuildContext context,
    ProductAnalyticData item,
    int rank,
    bool isTopThree,
  ) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          // Rank badge
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: isTopThree
                  ? AppColor.primary.withOpacity(0.1)
                  : AppColor.textSecondary.withOpacity(0.08),
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              '$rank',
              style: AppStyle.md.copyWith(
                color: isTopThree ? AppColor.primary : AppColor.textSecondary,
                fontWeight: FontWeight.w700,
                fontSize: 14,
              ),
            ),
          ),
          const SpaceWidth(12),

          // Product name + sold count
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.productName.toUpperCase(),
                  style: AppStyle.md.copyWith(
                    color: AppColor.textPrimary,
                    fontWeight: FontWeight.w700,
                    fontSize: 14,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Text(
                  '${item.quantitySold} ${context.lang.sold.toLowerCase()}',
                  style: AppStyle.sm.copyWith(
                    color: AppColor.textSecondary,
                    fontWeight: FontWeight.w400,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),

          // Revenue
          Text(
            item.revenue.currencyFormatRp,
            style: AppStyle.md.copyWith(
              color: AppColor.textPrimary,
              fontWeight: FontWeight.w600,
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildShimmer() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Shimmer.fromColors(
        baseColor: Colors.grey[300]!,
        highlightColor: Colors.grey[100]!,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 140,
                  height: 20,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                Container(
                  width: 70,
                  height: 14,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
              ],
            ),
            const SpaceHeight(20),
            ...List.generate(
              6,
              (index) => Padding(
                padding: const EdgeInsets.only(bottom: 16),
                child: Row(
                  children: [
                    Container(
                      width: 36,
                      height: 36,
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SpaceWidth(12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: 150,
                            height: 14,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(4),
                            ),
                          ),
                          const SizedBox(height: 4),
                          Container(
                            width: 60,
                            height: 12,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(4),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: 80,
                      height: 14,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(4),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
