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';

class SalesCategoryCard extends StatelessWidget {
  final CategoryAnalytic categoryAnalytic;
  final bool isFetching;

  const SalesCategoryCard({
    super.key,
    required this.categoryAnalytic,
    required this.isFetching,
  });

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

    final data = categoryAnalytic.data;
    final totalItems = data.fold<int>(0, (sum, e) => sum + e.totalQuantity);
    final totalRevenue = data.fold<int>(0, (sum, e) => sum + e.totalRevenue);

    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.sales_category,
                style: AppStyle.xl.copyWith(
                  fontWeight: FontWeight.bold,
                  color: AppColor.textPrimary,
                  fontSize: 18,
                ),
              ),
              Text(
                '$totalItems ${context.lang.item.toLowerCase()}',
                style: AppStyle.sm.copyWith(
                  color: AppColor.textSecondary,
                  fontWeight: FontWeight.w500,
                  fontSize: 13,
                ),
              ),
            ],
          ),
          const SpaceHeight(16),

          // Category items
          if (data.isEmpty)
            Center(
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 20),
                child: Text(
                  context.lang.category_no_data,
                  style: AppStyle.md.copyWith(color: AppColor.textSecondary),
                ),
              ),
            )
          else
            ...data.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              final percentage = totalRevenue > 0
                  ? (item.totalRevenue / totalRevenue * 100)
                  : 0.0;
              return Column(
                children: [
                  _buildCategoryItem(item, percentage, index),
                  if (index < data.length - 1) const SpaceHeight(16),
                ],
              );
            }),
        ],
      ),
    );
  }

  Widget _buildCategoryItem(
    CategoryAnalyticItem item,
    double percentage,
    int index,
  ) {
    final colors = [
      AppColor.primary,
      const Color(0xFF00BCD4),
      const Color(0xFFFF9800),
      const Color(0xFF9E9E9E),
      AppColor.success,
      AppColor.info,
    ];
    final color = colors[index % colors.length];

    return Column(
      children: [
        // Name + count + amount + percentage
        Row(
          children: [
            Expanded(
              child: Row(
                children: [
                  Flexible(
                    child: Text(
                      item.categoryName,
                      style: AppStyle.md.copyWith(
                        color: AppColor.textPrimary,
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SpaceWidth(8),
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 2,
                    ),
                    decoration: BoxDecoration(
                      color: AppColor.textSecondary.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Text(
                      '${item.totalQuantity}x',
                      style: AppStyle.xs.copyWith(
                        color: AppColor.textSecondary,
                        fontWeight: FontWeight.w600,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Text(
              item.totalRevenue.currencyFormatRp,
              style: AppStyle.md.copyWith(
                color: AppColor.textPrimary,
                fontWeight: FontWeight.w600,
                fontSize: 14,
              ),
            ),
            const SpaceWidth(6),
            Text(
              '${percentage.toStringAsFixed(1)}%',
              style: AppStyle.xs.copyWith(
                color: AppColor.textSecondary,
                fontWeight: FontWeight.w500,
                fontSize: 12,
              ),
            ),
          ],
        ),
        const SpaceHeight(8),
        // Progress bar
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: percentage / 100,
            minHeight: 6,
            backgroundColor: AppColor.border.withOpacity(0.3),
            valueColor: AlwaysStoppedAnimation<Color>(color),
          ),
        ),
      ],
    );
  }

  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: 160,
                  height: 20,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                Container(
                  width: 60,
                  height: 14,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
              ],
            ),
            const SpaceHeight(20),
            ...List.generate(
              4,
              (index) => Padding(
                padding: const EdgeInsets.only(bottom: 16),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          width: 120,
                          height: 14,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                        Container(
                          width: 90,
                          height: 14,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                      ],
                    ),
                    const SpaceHeight(8),
                    Container(
                      width: double.infinity,
                      height: 6,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(4),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
