import 'package:flutter/material.dart';

import '../../../../application/analytic/profit_sharing_loader/profit_sharing_loader_bloc.dart';
import '../../../../common/extension/extension.dart';
import '../../../../common/theme/theme.dart';
import '../../../../domain/analytic/analytic.dart';
import '../../../components/spacer/spacer.dart';
import 'period_label.dart';
import 'profit_sharing_allocation.dart';

class ProfitSharingPeriods extends StatelessWidget {
  final ProfitSharingLoaderState state;
  final ValueChanged<ProfitSharingPeriodType> onPeriodTypeChanged;

  const ProfitSharingPeriods({
    super.key,
    required this.state,
    required this.onPeriodTypeChanged,
  });

  @override
  Widget build(BuildContext context) {
    final periods = state.periods;
    final percentages = state.profitSharing.budget.percentages;

    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.period_breakdown,
            style: AppStyle.lg.copyWith(
              fontWeight: FontWeight.w700,
              color: AppColor.textPrimary,
            ),
          ),

          const SpaceHeight(16),

          _tabs(context),

          const SpaceHeight(16),

          if (periods.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
            ...periods.map(
              (period) => Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: _PeriodCard(period: period, percentages: percentages),
              ),
            ),
        ],
      ),
    );
  }

  Widget _tabs(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: AppColor.background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          _tab(
            context: context,
            label: context.lang.weekly,
            type: ProfitSharingPeriodType.weekly,
          ),
          _tab(
            context: context,
            label: context.lang.monthly,
            type: ProfitSharingPeriodType.monthly,
          ),
        ],
      ),
    );
  }

  Widget _tab({
    required BuildContext context,
    required String label,
    required ProfitSharingPeriodType type,
  }) {
    final isSelected = state.periodType == type;

    return Expanded(
      child: GestureDetector(
        onTap: () => onPeriodTypeChanged(type),
        behavior: HitTestBehavior.opaque,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(vertical: 10),
          decoration: BoxDecoration(
            color: isSelected ? AppColor.primary : Colors.transparent,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Text(
            label,
            textAlign: TextAlign.center,
            style: AppStyle.sm.copyWith(
              color: isSelected ? AppColor.textWhite : AppColor.textSecondary,
              fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }
}

class _PeriodCard extends StatelessWidget {
  final ProfitSharingPeriod period;
  final ProfitSharingPercentage percentages;

  const _PeriodCard({required this.period, required this.percentages});

  @override
  Widget build(BuildContext context) {
    final isMonthly = period.month.isNotEmpty;

    final title = isMonthly
        ? formatMonthLabel(period.month, period.periodStart)
        : formatPeriodLabel(period.periodStart, period.periodEnd);

    final subtitle = isMonthly
        ? '${formatPeriodLabel(period.periodStart, period.periodEnd)} - ${context.lang.week_count(period.weekCount)}'
        : context.lang.order_count_label(period.orderCount);

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColor.background,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColor.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: AppStyle.md.copyWith(
                        fontWeight: FontWeight.w700,
                        color: AppColor.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      subtitle,
                      style: AppStyle.xs.copyWith(
                        color: AppColor.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
              const SpaceWidth(8),
              Text(
                period.revenue.currencyFormatRp,
                style: AppStyle.md.copyWith(
                  fontWeight: FontWeight.w800,
                  color: AppColor.primary,
                ),
              ),
            ],
          ),

          const SpaceHeight(12),

          ProfitSharingBar(
            purchase: percentages.purchase,
            owner: percentages.owner,
            team: percentages.team,
            height: 6,
          ),

          const SpaceHeight(12),

          Row(
            children: [
              _share(
                context.lang.share_purchase,
                period.limitPurchase,
                ProfitSharingColor.purchase,
              ),
              _share(
                context.lang.share_owner,
                period.limitOwner,
                ProfitSharingColor.owner,
              ),
              _share(
                context.lang.share_team,
                period.limitTeam,
                ProfitSharingColor.team,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _share(String label, int amount, Color color) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 8,
                height: 8,
                decoration: BoxDecoration(color: color, shape: BoxShape.circle),
              ),
              const SpaceWidth(6),
              Flexible(
                child: Text(
                  label,
                  style: AppStyle.xs.copyWith(color: AppColor.textSecondary),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            amount.currencyFormatRp,
            style: AppStyle.xs.copyWith(
              color: AppColor.textPrimary,
              fontWeight: FontWeight.w700,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
}
