import 'package:flutter/material.dart';

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

/// Daftar sub kategori; tiap kartu bisa dibuka untuk melihat produknya.
class ProfitSharingSubCategories extends StatelessWidget {
  final List<ProfitSharingSubCategory> categories;
  final String expandedCategoryId;
  final ValueChanged<String> onToggle;

  const ProfitSharingSubCategories({
    super.key,
    required this.categories,
    required this.expandedCategoryId,
    required this.onToggle,
  });

  @override
  Widget build(BuildContext context) {
    final sorted = [...categories]
      ..sort((a, b) => b.totalRevenue.compareTo(a.totalRevenue));

    final totalRevenue = sorted.fold<int>(0, (sum, e) => sum + e.totalRevenue);

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: AppColor.textLight.withOpacity(0.08),
            spreadRadius: 1,
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            context.lang.sub_category,
            style: AppStyle.lg.copyWith(
              fontWeight: FontWeight.w700,
              color: AppColor.textPrimary,
            ),
          ),

          const SpaceHeight(16),

          if (sorted.isEmpty)
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 24),
              child: Center(
                child: Text(
                  context.lang.no_data_yet,
                  style: AppStyle.sm.copyWith(color: AppColor.textSecondary),
                ),
              ),
            )
          else
            ...sorted.map(
              (category) => Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: _SubCategoryCard(
                  category: category,
                  share: totalRevenue == 0
                      ? 0
                      : category.totalRevenue / totalRevenue,
                  isExpanded: expandedCategoryId == category.categoryId,
                  onToggle: () => onToggle(category.categoryId),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

class _SubCategoryCard extends StatelessWidget {
  final ProfitSharingSubCategory category;
  final double share;
  final bool isExpanded;
  final VoidCallback onToggle;

  const _SubCategoryCard({
    required this.category,
    required this.share,
    required this.isExpanded,
    required this.onToggle,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: AppColor.background,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColor.borderLight),
      ),
      child: Column(
        children: [
          InkWell(
            onTap: onToggle,
            borderRadius: BorderRadius.circular(12),
            child: Padding(
              padding: const EdgeInsets.all(14),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          category.categoryName,
                          style: AppStyle.md.copyWith(
                            color: AppColor.textPrimary,
                            fontWeight: FontWeight.w700,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SpaceWidth(8),
                      Text(
                        category.totalRevenue.currencyFormatRp,
                        style: AppStyle.md.copyWith(
                          color: AppColor.primary,
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                      AnimatedRotation(
                        turns: isExpanded ? 0.5 : 0,
                        duration: const Duration(milliseconds: 200),
                        child: const Icon(
                          Icons.keyboard_arrow_down_rounded,
                          color: AppColor.textSecondary,
                          size: 22,
                        ),
                      ),
                    ],
                  ),

                  const SpaceHeight(8),

                  ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: LinearProgressIndicator(
                      value: share.clamp(0.0, 1.0),
                      minHeight: 5,
                      backgroundColor: AppColor.borderLight,
                      valueColor: const AlwaysStoppedAnimation<Color>(
                        AppColor.primary,
                      ),
                    ),
                  ),

                  const SpaceHeight(12),

                  Row(
                    children: [
                      Expanded(
                        child: ProfitSharingMetric(
                          label: context.lang.qty,
                          value: category.totalQuantity.thousandFormat,
                        ),
                      ),
                      Expanded(
                        child: ProfitSharingMetric(
                          label: context.lang.products,
                          value: '${category.productCount}',
                        ),
                      ),
                      Expanded(
                        child: ProfitSharingMetric(
                          label: context.lang.real_hpp,
                          value: formatPercent(category.realHppPercentage),
                          valueColor: statusColor(category.realHppPercentage),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          AnimatedCrossFade(
            duration: const Duration(milliseconds: 200),
            crossFadeState: isExpanded
                ? CrossFadeState.showFirst
                : CrossFadeState.showSecond,
            firstChild: _ProductList(products: category.products),
            secondChild: const SizedBox(width: double.infinity),
          ),
        ],
      ),
    );
  }
}

class _ProductList extends StatelessWidget {
  final List<ProfitSharingProduct> products;

  const _ProductList({required this.products});

  @override
  Widget build(BuildContext context) {
    final sorted = [...products]
      ..sort((a, b) => b.revenue.compareTo(a.revenue));

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(14, 0, 14, 14),
      child: Column(
        children: [
          const Divider(height: 1, color: AppColor.border),
          const SpaceHeight(10),
          ...sorted.map((product) => _ProductRow(product: product)),
        ],
      ),
    );
  }
}

class _ProductRow extends StatelessWidget {
  final ProfitSharingProduct product;

  const _ProductRow({required this.product});

  @override
  Widget build(BuildContext context) {
    final color = statusColor(product.realHppPercentage);

    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(top: 4),
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
            decoration: BoxDecoration(
              color: AppColor.primary.withOpacity(0.08),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Text(
              '${product.quantitySold}x',
              style: AppStyle.xs.copyWith(
                color: AppColor.primary,
                fontWeight: FontWeight.w700,
              ),
            ),
          ),
          const SpaceWidth(10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  product.productName,
                  style: AppStyle.sm.copyWith(
                    color: AppColor.textPrimary,
                    fontWeight: FontWeight.w600,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Text(
                  '${product.productSku} · @${product.averagePrice.round().currencyFormatRp}',
                  style: AppStyle.xs.copyWith(color: AppColor.textSecondary),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SpaceWidth(8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                product.revenue.currencyFormatRp,
                style: AppStyle.sm.copyWith(
                  color: AppColor.textPrimary,
                  fontWeight: FontWeight.w700,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                '${context.lang.real_hpp} ${formatPercent(product.realHppPercentage)}',
                style: AppStyle.xs.copyWith(
                  color: color,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
