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

import '../../../../../../../common/extension/extension.dart';
import '../../../../../../../common/function/app_function.dart';
import '../../../../../../../common/theme/theme.dart';
import '../../../../../../../domain/analytic/analytic.dart';
import '../../../../../../components/spaces/space.dart';

class ReportProfitLossMetric extends StatelessWidget {
  final ProfitLossAnalytic data;
  const ReportProfitLossMetric({super.key, required this.data});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: const EdgeInsets.only(top: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Metrik Kinerja Terperinci',
            style: AppStyle.xl.copyWith(
              fontWeight: FontWeight.bold,
              color: AppColor.textPrimary,
            ),
          ),
          const SpaceHeight(16),

          Row(
            children: [
              Expanded(
                child: _buildMetricCard(
                  'Nilai Rata-rata Pesanan',
                  _safeCalculateAverageOrder().currencyFormatRpV2,
                  'Per transaksi',
                  Icons.shopping_cart_outlined,
                  AppColor.info,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: _buildMetricCard(
                  'Keuntungan Rata-rata',
                  "${data.summary.averageProfit.round()}%",
                  'Per pesanan',
                  Icons.trending_up,
                  AppColor.success,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: _buildMetricCard(
                  'Rasio Biaya',
                  '${_safeCalculateCostRatio()}%',
                  'Dari total pendapatan',
                  Icons.pie_chart,
                  AppColor.error,
                ),
              ),
            ],
          ),

          const SpaceHeight(16),

          // Tabel rincian harian
          Container(
            decoration: BoxDecoration(
              color: const Color(0xFFF8FAFC),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey[100]!),
            ),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: AppColor.primary.withOpacity(0.05),
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(12),
                      topRight: Radius.circular(12),
                    ),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 2,
                        child: Text(
                          'Tanggal',
                          style: AppStyle.sm.copyWith(
                            fontWeight: FontWeight.bold,
                            color: AppColor.textPrimary,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          'Pendapatan',
                          textAlign: TextAlign.center,
                          style: AppStyle.sm.copyWith(
                            fontWeight: FontWeight.bold,
                            color: AppColor.textPrimary,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          'Biaya',
                          textAlign: TextAlign.center,
                          style: AppStyle.sm.copyWith(
                            fontWeight: FontWeight.bold,
                            color: AppColor.textPrimary,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          'Laba Bersih',
                          textAlign: TextAlign.center,
                          style: AppStyle.sm.copyWith(
                            fontWeight: FontWeight.bold,
                            color: AppColor.textPrimary,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          'Margin',
                          textAlign: TextAlign.center,
                          style: AppStyle.sm.copyWith(
                            fontWeight: FontWeight.bold,
                            color: AppColor.textPrimary,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                ...data.data.map((item) {
                  final date = DateTime.parse(item.date);
                  final dateStr = DateFormat('dd MMM').format(date);

                  return Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(color: Colors.grey[100]!),
                      ),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Text(
                            dateStr,
                            style: AppStyle.sm.copyWith(
                              fontWeight: FontWeight.w600,
                              color: AppColor.textPrimary,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Text(
                            item.revenue.currencyFormatRpV2,
                            textAlign: TextAlign.center,
                            style: AppStyle.xs.copyWith(
                              fontWeight: FontWeight.w500,
                              color: AppColor.info,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Text(
                            item.cost.toString().currencyFormatRpV2,
                            textAlign: TextAlign.center,
                            style: AppStyle.xs.copyWith(
                              fontWeight: FontWeight.w500,
                              color: AppColor.error,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Text(
                            item.netProfit.toString().currencyFormatRpV2,
                            textAlign: TextAlign.center,
                            style: AppStyle.xs.copyWith(
                              fontWeight: FontWeight.w600,
                              color: AppColor.success,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 3,
                            ),
                            decoration: BoxDecoration(
                              color: _getMarginColor(
                                item.netProfitMargin,
                              ).withOpacity(0.1),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              '${safeRound(item.netProfitMargin)}%',
                              textAlign: TextAlign.center,
                              style: AppStyle.xs.copyWith(
                                fontSize: 10,
                                fontWeight: FontWeight.bold,
                                color: _getMarginColor(item.netProfitMargin),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                }),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMetricCard(
    String title,
    String value,
    String subtitle,
    IconData icon,
    Color color,
  ) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: color.withOpacity(0.06),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.2)),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 24),
          const SpaceHeight(8),
          Text(
            value,
            style: AppStyle.lg.copyWith(
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SpaceHeight(4),
          Text(
            title,
            textAlign: TextAlign.center,
            style: AppStyle.sm.copyWith(
              fontWeight: FontWeight.w600,
              color: AppColor.textPrimary,
            ),
          ),
          const SpaceHeight(2),
          Text(
            subtitle,
            textAlign: TextAlign.center,
            style: AppStyle.xs.copyWith(
              fontSize: 10,
              color: AppColor.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  int _safeCalculateAverageOrder() {
    if (data.summary.totalOrders == 0) return 0;
    final average = data.summary.totalRevenue / data.summary.totalOrders;
    if (average.isNaN || average.isInfinite) return 0;
    return average.round();
  }

  int _safeCalculateCostRatio() {
    if (data.summary.totalRevenue == 0) return 0;
    final ratio = (data.summary.totalCost / data.summary.totalRevenue) * 100;
    if (ratio.isNaN || ratio.isInfinite) return 0;
    return ratio.round();
  }

  Color _getMarginColor(double margin) {
    final safeMargin = safeDouble(margin);
    if (safeMargin >= 25) return AppColor.success;
    if (safeMargin >= 15) return AppColor.warning;
    return AppColor.error;
  }
}
