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

/// Ringkasan omzet & HPP per kategori induk (parent category).
/// Tiap kartu bisa diketuk untuk melihat rincian sub kategori & produknya.
class ProfitSharingCategories extends StatelessWidget {
  final List<ProfitSharingCategory> categories;
  final ValueChanged<ProfitSharingCategory> onCategoryTap;

  const ProfitSharingCategories({
    super.key,
    required this.categories,
    required this.onCategoryTap,
  });

  @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.parent_category_summary,
            style: AppStyle.lg.copyWith(
              fontWeight: FontWeight.w700,
              color: AppColor.textPrimary,
            ),
          ),
          const SizedBox(height: 2),
          Text(
            context.lang.tap_row_for_detail,
            style: AppStyle.xs.copyWith(color: AppColor.textSecondary),
          ),

          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: _CategoryCard(
                  category: category,
                  share: totalRevenue == 0
                      ? 0
                      : category.totalRevenue / totalRevenue,
                  onTap: () => onCategoryTap(category),
                ),
              ),
            ),
            _TotalCard(categories: sorted),
          ],
        ],
      ),
    );
  }
}

class _CategoryCard extends StatelessWidget {
  final ProfitSharingCategory category;
  final double share;
  final VoidCallback onTap;

  const _CategoryCard({
    required this.category,
    required this.share,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: AppColor.background,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: AppColor.borderLight),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    category.parentCategoryName,
                    style: AppStyle.md.copyWith(
                      color: AppColor.textPrimary,
                      fontWeight: FontWeight.w700,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SpaceWidth(8),
                ProfitSharingStatusBadge(
                  realHppPercentage: category.realHppPercentage,
                ),
                const Icon(
                  Icons.chevron_right_rounded,
                  color: AppColor.textSecondary,
                  size: 20,
                ),
              ],
            ),

            const SpaceHeight(8),

            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  child: Text(
                    category.totalRevenue.currencyFormatRp,
                    style: AppStyle.lg.copyWith(
                      color: AppColor.primary,
                      fontWeight: FontWeight.w800,
                    ),
                  ),
                ),
                Text(
                  formatPercent(share * 100),
                  style: AppStyle.xs.copyWith(
                    color: AppColor.textSecondary,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),

            const SpaceHeight(8),

            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: LinearProgressIndicator(
                value: share.clamp(0.0, 1.0),
                minHeight: 6,
                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.sub_category,
                    value: '${category.categoryCount}',
                  ),
                ),
              ],
            ),

            const Padding(
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Divider(height: 1, color: AppColor.border),
            ),

            Row(
              children: [
                Expanded(
                  child: ProfitSharingMetric(
                    label: context.lang.std_hpp,
                    value: formatPercent(category.standardHppPercentage),
                  ),
                ),
                Expanded(
                  child: ProfitSharingMetric(
                    label: context.lang.real_hpp,
                    value: formatPercent(category.realHppPercentage),
                    valueColor: statusColor(category.realHppPercentage),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class _TotalCard extends StatelessWidget {
  final List<ProfitSharingCategory> categories;

  const _TotalCard({required this.categories});

  @override
  Widget build(BuildContext context) {
    final totalQuantity = categories.fold<int>(
      0,
      (sum, e) => sum + e.totalQuantity,
    );
    final totalRevenue = categories.fold<int>(
      0,
      (sum, e) => sum + e.totalRevenue,
    );
    final totalStandardHpp = categories.fold<int>(
      0,
      (sum, e) => sum + e.totalStandardHpp,
    );
    final totalFifoHpp = categories.fold<int>(
      0,
      (sum, e) => sum + e.totalFifoHpp,
    );

    double percentOf(int hpp) =>
        totalRevenue == 0 ? 0 : (hpp / totalRevenue) * 100;

    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: AppColor.primary.withOpacity(0.06),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  context.lang.grand_total,
                  style: AppStyle.md.copyWith(
                    color: AppColor.textPrimary,
                    fontWeight: FontWeight.w800,
                  ),
                ),
              ),
              Text(
                totalRevenue.currencyFormatRp,
                style: AppStyle.lg.copyWith(
                  color: AppColor.primary,
                  fontWeight: FontWeight.w900,
                ),
              ),
            ],
          ),

          const SpaceHeight(12),

          Row(
            children: [
              Expanded(
                child: ProfitSharingMetric(
                  label: context.lang.qty,
                  value: totalQuantity.thousandFormat,
                  isBold: true,
                ),
              ),
              Expanded(
                child: ProfitSharingMetric(
                  label: context.lang.std_hpp,
                  value: formatPercent(percentOf(totalStandardHpp)),
                  isBold: true,
                ),
              ),
              Expanded(
                child: ProfitSharingMetric(
                  label: context.lang.real_hpp,
                  value: formatPercent(percentOf(totalFifoHpp)),
                  isBold: true,
                  valueColor: statusColor(percentOf(totalFifoHpp)),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
