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

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

class InventoryStockReport extends StatelessWidget {
  final InventoryAnalytic inventoryAnalytic;
  final int selectedTabIndex;

  const InventoryStockReport({
    super.key,
    required this.inventoryAnalytic,
    required this.selectedTabIndex,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(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: [
          // Title row
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                selectedTabIndex == 0
                    ? context.lang.product
                    : context.lang.ingredients,
                style: AppStyle.lg.copyWith(
                  fontWeight: FontWeight.w700,
                  color: AppColor.textPrimary,
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 10,
                  vertical: 4,
                ),
                decoration: BoxDecoration(
                  color: AppColor.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  selectedTabIndex == 0
                      ? '${inventoryAnalytic.products.length} item'
                      : '${inventoryAnalytic.ingredients.length} item',
                  style: AppStyle.sm.copyWith(
                    color: AppColor.primary,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),

          const SpaceHeight(16),

          // Summary stats row
          _buildSummaryStats(context),

          const SpaceHeight(16),

          const Divider(height: 1, color: AppColor.borderLight),

          const SpaceHeight(12),

          // Table header
          _buildTableHeader(context),

          const SpaceHeight(8),

          // Items list
          if (selectedTabIndex == 0)
            ...inventoryAnalytic.products.map(
              (product) => _buildProductRow(context, product),
            )
          else
            ...inventoryAnalytic.ingredients.map(
              (ingredient) => _buildIngredientRow(context, ingredient),
            ),

          const SpaceHeight(12),

          // Footer totals
          _buildFooterTotals(context),
        ],
      ),
    );
  }

  Widget _buildSummaryStats(BuildContext context) {
    final summary = inventoryAnalytic.summary;

    if (selectedTabIndex == 0) {
      return Row(
        children: [
          Expanded(
            child: _buildMiniStat(
              context.lang.total_sold,
              summary.totalSoldProducts.toString(),
              AppColor.success,
              Icons.check_circle_rounded,
            ),
          ),
          const SpaceWidth(8),
          Expanded(
            child: _buildMiniStat(
              context.lang.low_stock,
              summary.lowStockProducts.toString(),
              AppColor.warning,
              Icons.warning_rounded,
            ),
          ),
          const SpaceWidth(8),
          Expanded(
            child: _buildMiniStat(
              context.lang.zero_stock,
              summary.zeroStockProducts.toString(),
              AppColor.error,
              Icons.error_rounded,
            ),
          ),
        ],
      );
    } else {
      return Row(
        children: [
          Expanded(
            child: _buildMiniStat(
              context.lang.total_sold,
              summary.totalSoldIngredients.toString(),
              AppColor.success,
              Icons.check_circle_rounded,
            ),
          ),
          const SpaceWidth(8),
          Expanded(
            child: _buildMiniStat(
              context.lang.low_stock,
              summary.lowStockIngredients.toString(),
              AppColor.warning,
              Icons.warning_rounded,
            ),
          ),
          const SpaceWidth(8),
          Expanded(
            child: _buildMiniStat(
              context.lang.zero_stock,
              summary.zeroStockIngredients.toString(),
              AppColor.error,
              Icons.error_rounded,
            ),
          ),
        ],
      );
    }
  }

  Widget _buildMiniStat(
    String label,
    String value,
    Color color,
    IconData icon,
  ) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
      decoration: BoxDecoration(
        color: color.withOpacity(0.08),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Icon(icon, size: 18, color: color),
          const SpaceHeight(4),
          Text(
            value,
            style: AppStyle.lg.copyWith(
              fontWeight: FontWeight.w800,
              color: color,
            ),
          ),
          const SpaceHeight(2),
          Text(
            label,
            style: AppStyle.xs.copyWith(
              color: color.withOpacity(0.8),
              fontWeight: FontWeight.w500,
              fontSize: 10,
            ),
            textAlign: TextAlign.center,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  Widget _buildTableHeader(BuildContext context) {
    if (selectedTabIndex == 0) {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            Expanded(
              flex: 4,
              child: Text(
                context.lang.product,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Text(
                context.lang.stock,
                textAlign: TextAlign.center,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Text(
                context.lang.in_text,
                textAlign: TextAlign.center,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Text(
                context.lang.out_text,
                textAlign: TextAlign.center,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
          ],
        ),
      );
    } else {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            Expanded(
              flex: 4,
              child: Text(
                context.lang.ingredients,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Text(
                context.lang.stock,
                textAlign: TextAlign.center,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Text(
                context.lang.in_text,
                textAlign: TextAlign.center,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Text(
                context.lang.out_text,
                textAlign: TextAlign.center,
                style: AppStyle.sm.copyWith(
                  fontWeight: FontWeight.w600,
                  color: AppColor.textSecondary,
                ),
              ),
            ),
          ],
        ),
      );
    }
  }

  Widget _buildProductRow(BuildContext context, InventoryProduct product) {
    final statusColor = product.isZeroStock
        ? AppColor.error
        : product.isLowStock
        ? AppColor.warning
        : AppColor.textPrimary;

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 10),
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(color: AppColor.borderLight, width: 0.5),
        ),
      ),
      child: Row(
        children: [
          // Product name + category
          Expanded(
            flex: 4,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  product.productName,
                  style: AppStyle.md.copyWith(
                    fontWeight: FontWeight.w600,
                    color: AppColor.textPrimary,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SpaceHeight(2),
                Row(
                  children: [
                    if (product.isZeroStock || product.isLowStock)
                      Container(
                        width: 6,
                        height: 6,
                        margin: const EdgeInsets.only(right: 4),
                        decoration: BoxDecoration(
                          color: statusColor,
                          shape: BoxShape.circle,
                        ),
                      ),
                    Flexible(
                      child: Text(
                        product.categoryName,
                        style: AppStyle.xs.copyWith(
                          color: AppColor.textSecondary,
                          fontWeight: FontWeight.w400,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // Stock
          Expanded(
            flex: 2,
            child: Text(
              NumberFormat('#,###', 'id_ID').format(product.quantity),
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w600,
                color: statusColor,
              ),
            ),
          ),

          // In
          Expanded(
            flex: 2,
            child: Text(
              product.totalIn > 0
                  ? '+${NumberFormat('#,###', 'id_ID').format(product.totalIn)}'
                  : '-',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w500,
                color: product.totalIn > 0
                    ? AppColor.success
                    : AppColor.textSecondary,
              ),
            ),
          ),

          // Out
          Expanded(
            flex: 2,
            child: Text(
              product.totalOut > 0
                  ? '-${NumberFormat('#,###', 'id_ID').format(product.totalOut)}'
                  : '-',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w500,
                color: product.totalOut > 0
                    ? AppColor.error
                    : AppColor.textSecondary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildIngredientRow(
    BuildContext context,
    InventoryIngredient ingredient,
  ) {
    final statusColor = ingredient.isZeroStock
        ? AppColor.error
        : ingredient.isLowStock
        ? AppColor.warning
        : AppColor.textPrimary;

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 10),
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(color: AppColor.borderLight, width: 0.5),
        ),
      ),
      child: Row(
        children: [
          // Ingredient name + unit
          Expanded(
            flex: 4,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  ingredient.ingredientName,
                  style: AppStyle.md.copyWith(
                    fontWeight: FontWeight.w600,
                    color: AppColor.textPrimary,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SpaceHeight(2),
                Row(
                  children: [
                    if (ingredient.isZeroStock || ingredient.isLowStock)
                      Container(
                        width: 6,
                        height: 6,
                        margin: const EdgeInsets.only(right: 4),
                        decoration: BoxDecoration(
                          color: statusColor,
                          shape: BoxShape.circle,
                        ),
                      ),
                    Flexible(
                      child: Text(
                        ingredient.unitName,
                        style: AppStyle.xs.copyWith(
                          color: AppColor.textSecondary,
                          fontWeight: FontWeight.w400,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // Stock
          Expanded(
            flex: 2,
            child: Text(
              NumberFormat('#,###', 'id_ID').format(ingredient.quantity),
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w600,
                color: statusColor,
              ),
            ),
          ),

          // In
          Expanded(
            flex: 2,
            child: Text(
              ingredient.totalIn > 0
                  ? '+${NumberFormat('#,###', 'id_ID').format(ingredient.totalIn)}'
                  : '-',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w500,
                color: ingredient.totalIn > 0
                    ? AppColor.success
                    : AppColor.textSecondary,
              ),
            ),
          ),

          // Out
          Expanded(
            flex: 2,
            child: Text(
              ingredient.totalOut > 0
                  ? '-${NumberFormat('#,###', 'id_ID').format(ingredient.totalOut)}'
                  : '-',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w500,
                color: ingredient.totalOut > 0
                    ? AppColor.error
                    : AppColor.textSecondary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFooterTotals(BuildContext context) {
    int totalStock;
    int totalIn;
    int totalOut;

    if (selectedTabIndex == 0) {
      totalStock = inventoryAnalytic.products.fold<int>(
        0,
        (sum, item) => sum + item.quantity,
      );
      totalIn = inventoryAnalytic.products.fold<int>(
        0,
        (sum, item) => sum + item.totalIn,
      );
      totalOut = inventoryAnalytic.products.fold<int>(
        0,
        (sum, item) => sum + item.totalOut,
      );
    } else {
      totalStock = inventoryAnalytic.ingredients.fold<int>(
        0,
        (sum, item) => sum + item.quantity,
      );
      totalIn = inventoryAnalytic.ingredients.fold<int>(
        0,
        (sum, item) => sum + item.totalIn,
      );
      totalOut = inventoryAnalytic.ingredients.fold<int>(
        0,
        (sum, item) => sum + item.totalOut,
      );
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
      decoration: BoxDecoration(
        color: AppColor.primary.withOpacity(0.08),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Expanded(
            flex: 4,
            child: Text(
              'TOTAL',
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w700,
                color: AppColor.primary,
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              NumberFormat('#,###', 'id_ID').format(totalStock),
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w700,
                color: AppColor.primary,
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              '+${NumberFormat('#,###', 'id_ID').format(totalIn)}',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w700,
                color: AppColor.success,
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              '-${NumberFormat('#,###', 'id_ID').format(totalOut)}',
              textAlign: TextAlign.center,
              style: AppStyle.md.copyWith(
                fontWeight: FontWeight.w700,
                color: AppColor.error,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
