import 'package:flutter/material.dart';
import 'package:line_icons/line_icons.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 InventoryProductTile extends StatelessWidget {
  final InventoryProduct item;
  const InventoryProductTile({super.key, required this.item});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: _getStatusColor().withOpacity(0.2),
          width: 1.5,
        ),
        boxShadow: [
          BoxShadow(
            color: _getStatusColor().withOpacity(0.06),
            blurRadius: 16,
            offset: const Offset(0, 6),
          ),
          BoxShadow(
            color: AppColor.textLight.withOpacity(0.08),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          // Main Content Row
          Row(
            children: [
              // Enhanced Product Icon
              Container(
                width: 70,
                height: 70,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: _getGradientColors(),
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(18),
                  boxShadow: [
                    BoxShadow(
                      color: _getStatusColor().withOpacity(0.25),
                      blurRadius: 12,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Stack(
                  children: [
                    Center(
                      child: Icon(
                        _getCategoryIcon(),
                        size: 32,
                        color: AppColor.white,
                      ),
                    ),
                    // Status indicator
                    Positioned(
                      top: 6,
                      right: 6,
                      child: Container(
                        width: 14,
                        height: 14,
                        decoration: BoxDecoration(
                          color: AppColor.white,
                          shape: BoxShape.circle,
                          border: Border.all(
                            color: _getStatusColor(),
                            width: 2.5,
                          ),
                        ),
                        child: Center(
                          child: Container(
                            width: 5,
                            height: 5,
                            decoration: BoxDecoration(
                              color: _getStatusColor(),
                              shape: BoxShape.circle,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              const SpaceWidth(16),

              // Product Information
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Product Name and Category Row
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            item.productName,
                            style: AppStyle.lg.copyWith(
                              fontWeight: FontWeight.w700,
                              color: AppColor.textPrimary,
                              height: 1.2,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SpaceWidth(8),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: AppColor.primary.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(10),
                            border: Border.all(
                              color: AppColor.primary.withOpacity(0.15),
                              width: 0.5,
                            ),
                          ),
                          child: Text(
                            item.categoryName,
                            style: AppStyle.xs.copyWith(
                              fontSize: 9,
                              fontWeight: FontWeight.w600,
                              color: AppColor.primary,
                              letterSpacing: 0.2,
                            ),
                          ),
                        ),
                      ],
                    ),

                    SpaceHeight(8),

                    // Price and Status Row
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // Price
                        Text(
                          item.unitCost.currencyFormatRp,
                          style: AppStyle.md.copyWith(
                            fontWeight: FontWeight.w800,
                            color: AppColor.success,
                            fontSize: 16,
                          ),
                        ),
                        // Status Badge
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: _getStatusColor(),
                            borderRadius: BorderRadius.circular(12),
                            boxShadow: [
                              BoxShadow(
                                color: _getStatusColor().withOpacity(0.3),
                                blurRadius: 6,
                                offset: const Offset(0, 2),
                              ),
                            ],
                          ),
                          child: Text(
                            item.isZeroStock
                                ? context.lang.out_of_stock
                                : item.isLowStock
                                ? context.lang.low_stock
                                : context.lang.available,
                            style: AppStyle.xs.copyWith(
                              fontSize: 10,
                              fontWeight: FontWeight.w700,
                              color: AppColor.white,
                            ),
                          ),
                        ),
                      ],
                    ),

                    SpaceHeight(10),

                    // Stock Information Grid
                    Row(
                      children: [
                        // Quantity Info
                        Expanded(
                          child: _buildInfoItem(
                            LineIcons.boxes,
                            context.lang.stock,
                            '${NumberFormat('#,###', 'id_ID').format(item.quantity)} pcs',
                            _getQuantityColor(),
                          ),
                        ),
                        const SpaceWidth(16),
                        // Total Value Info
                        Expanded(
                          child: _buildInfoItem(
                            LineIcons.dollarSign,
                            context.lang.value_text,
                            _formatCurrencyShort(item.totalValue),
                            AppColor.info,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),

          // Additional Information (conditionally shown)
          if (_shouldShowAdditionalInfo()) ...[
            SpaceHeight(12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColor.background,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: AppColor.borderLight, width: 0.5),
              ),
              child: Column(
                children: [
                  // Low Stock Warning
                  if (item.isLowStock && !item.isZeroStock) ...[
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(
                            color: AppColor.warning.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(
                            LineIcons.exclamationTriangle,
                            size: 16,
                            color: AppColor.warning,
                          ),
                        ),
                        const SpaceWidth(10),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                context.lang.low_stock,
                                style: AppStyle.sm.copyWith(
                                  fontWeight: FontWeight.w600,
                                  color: AppColor.warning,
                                ),
                              ),
                              Text(
                                context.lang.low_stock_desc(
                                  NumberFormat(
                                    '#,###',
                                    'id_ID',
                                  ).format(item.reorderLevel),
                                ),
                                style: AppStyle.xs.copyWith(
                                  color: AppColor.textSecondary,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],

                  // Zero Stock Warning
                  if (item.isZeroStock) ...[
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(
                            color: AppColor.error.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(
                            LineIcons.timesCircle,
                            size: 16,
                            color: AppColor.error,
                          ),
                        ),
                        const SpaceWidth(10),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                context.lang.out_of_stock,
                                style: AppStyle.sm.copyWith(
                                  fontWeight: FontWeight.w600,
                                  color: AppColor.error,
                                ),
                              ),
                              Text(
                                context.lang.out_of_stock_desc,
                                style: AppStyle.xs.copyWith(
                                  color: AppColor.textSecondary,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],

                  // Movement Information
                  if (_hasMovementData()) ...[
                    if ((item.isLowStock || item.isZeroStock)) SpaceHeight(12),
                    Row(
                      children: [
                        if (item.totalIn > 0)
                          Expanded(
                            child: _buildMovementInfo(
                              LineIcons.arrowUp,
                              context.lang.in_text,
                              '${NumberFormat('#,###', 'id_ID').format(item.totalIn)} pcs',
                              AppColor.success,
                            ),
                          ),
                        if (item.totalIn > 0 && item.totalOut > 0)
                          const SpaceWidth(16),
                        if (item.totalOut > 0)
                          Expanded(
                            child: _buildMovementInfo(
                              LineIcons.arrowDown,
                              context.lang.out_text,
                              '${NumberFormat('#,###', 'id_ID').format(item.totalOut)} pcs',
                              AppColor.error,
                            ),
                          ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildInfoItem(
    IconData icon,
    String label,
    String value,
    Color valueColor,
  ) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
      decoration: BoxDecoration(
        color: AppColor.background,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: AppColor.borderLight, width: 0.5),
      ),
      child: Row(
        children: [
          Icon(icon, size: 14, color: AppColor.textSecondary),
          const SpaceWidth(6),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: AppStyle.xs.copyWith(
                    fontSize: 10,
                    fontWeight: FontWeight.w500,
                    color: AppColor.textSecondary,
                  ),
                ),
                SpaceHeight(1),
                Text(
                  value,
                  style: AppStyle.xs.copyWith(
                    fontSize: 11,
                    fontWeight: FontWeight.w700,
                    color: valueColor,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMovementInfo(
    IconData icon,
    String label,
    String value,
    Color color,
  ) {
    return Row(
      children: [
        Container(
          padding: const EdgeInsets.all(4),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Icon(icon, size: 12, color: color),
        ),
        const SpaceWidth(8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              label,
              style: AppStyle.xs.copyWith(
                color: AppColor.textSecondary,
                fontWeight: FontWeight.w500,
              ),
            ),
            Text(
              value,
              style: AppStyle.xs.copyWith(
                color: color,
                fontWeight: FontWeight.w700,
                fontSize: 11,
              ),
            ),
          ],
        ),
      ],
    );
  }

  // Helper methods
  bool _shouldShowAdditionalInfo() {
    return item.isLowStock || item.isZeroStock || _hasMovementData();
  }

  bool _hasMovementData() {
    return item.totalIn > 0 || item.totalOut > 0;
  }

  Color _getStatusColor() {
    if (item.isZeroStock) return AppColor.error;
    if (item.isLowStock) return AppColor.warning;
    return AppColor.success;
  }

  List<Color> _getGradientColors() {
    if (item.isZeroStock) {
      return [AppColor.error, AppColor.error.withOpacity(0.7)];
    }
    if (item.isLowStock) {
      return [AppColor.warning, AppColor.warning.withOpacity(0.7)];
    }
    return [AppColor.primary, AppColor.primary.withOpacity(0.7)];
  }

  Color _getQuantityColor() {
    if (item.isZeroStock) return AppColor.error;
    if (item.isLowStock) return AppColor.warning;
    return AppColor.textPrimary;
  }

  IconData _getCategoryIcon() {
    final category = item.categoryName.toLowerCase();
    if (category.contains('elektronik') || category.contains('gadget')) {
      return LineIcons.mobilePhone;
    } else if (category.contains('fashion') || category.contains('pakaian')) {
      return LineIcons.tShirt;
    } else if (category.contains('makanan') || category.contains('food')) {
      return LineIcons.utensils;
    } else if (category.contains('kesehatan') || category.contains('health')) {
      return LineIcons.medkit;
    } else if (category.contains('rumah') || category.contains('home')) {
      return LineIcons.home;
    } else if (category.contains('olahraga') || category.contains('sport')) {
      return LineIcons.dumbbell;
    }
    return LineIcons.box;
  }

  String _formatCurrencyShort(int amount) {
    if (amount.abs() >= 1000000000) {
      return 'Rp ${(amount / 1000000000).toStringAsFixed(1)}B';
    } else if (amount.abs() >= 1000000) {
      return 'Rp ${(amount / 1000000).toStringAsFixed(1)}M';
    } else if (amount.abs() >= 1000) {
      return 'Rp ${(amount / 1000).toStringAsFixed(0)}K';
    } else {
      return 'Rp ${NumberFormat('#,###', 'id_ID').format(amount)}';
    }
  }
}
