// ABOUTME: Widget for displaying individual weight entries in lists
// ABOUTME: Shows weight value with trend indicators and provides edit/delete actions
import 'package:flutter/material.dart';
import '../models/weight_entry.dart';
import '../utils/unit_converter.dart';
import '../utils/constants.dart';
import 'weight_input_widget.dart'; // For WeightUnit enum

class WeightListItem extends StatelessWidget {
  final WeightEntry entry;
  final WeightEntry? previousEntry;
  final WeightUnit displayUnit;
  final VoidCallback? onEdit;
  final VoidCallback? onDelete;

  const WeightListItem({
    super.key,
    required this.entry,
    this.previousEntry,
    this.displayUnit = WeightUnit.kg,
    this.onEdit,
    this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final displayWeight = UnitConverter.convertWeight(
      entry.weightKg,
      UnitConstants.kgUnit,
      displayUnit.unitString,
    );
    
    final trend = _calculateTrend();

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: theme.colorScheme.primaryContainer,
          child: Icon(
            Icons.monitor_weight,
            color: theme.colorScheme.onPrimaryContainer,
          ),
        ),
        title: Row(
          children: [
            Text(
              '${displayWeight.toStringAsFixed(1)} ${displayUnit.displayName}',
              style: theme.textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
            if (trend != null) ...[
              const SizedBox(width: 8),
              _buildTrendIndicator(context, trend),
            ],
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              _formatDateTime(entry.timestamp),
              style: theme.textTheme.bodySmall,
            ),
            if (entry.notes?.isNotEmpty == true) ...[
              const SizedBox(height: 4),
              Text(
                entry.notes!,
                style: theme.textTheme.bodySmall?.copyWith(
                  fontStyle: FontStyle.italic,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
            if (trend != null) ...[
              const SizedBox(height: 4),
              Text(
                trend.isNegative 
                    ? '${trend.abs().toStringAsFixed(1)} ${displayUnit.displayName} lost'
                    : '+${trend.toStringAsFixed(1)} ${displayUnit.displayName} gained',
                style: theme.textTheme.bodySmall?.copyWith(
                  color: trend.isNegative 
                      ? Colors.green 
                      : Colors.orange,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ],
        ),
        trailing: _buildActions(context),
        isThreeLine: (entry.notes?.isNotEmpty == true) || trend != null,
      ),
    );
  }

  double? _calculateTrend() {
    if (previousEntry == null) return null;
    
    final currentWeight = UnitConverter.convertWeight(
      entry.weightKg,
      UnitConstants.kgUnit,
      displayUnit.unitString,
    );
    
    final previousWeight = UnitConverter.convertWeight(
      previousEntry!.weightKg,
      UnitConstants.kgUnit,
      displayUnit.unitString,
    );
    
    return currentWeight - previousWeight;
  }

  Widget _buildTrendIndicator(BuildContext context, double trend) {
    final isPositive = trend > 0;
    final isNeutral = trend.abs() < 0.1; // Less than 0.1 unit change
    
    IconData icon;
    Color color;
    
    if (isNeutral) {
      icon = Icons.trending_flat;
      color = Theme.of(context).colorScheme.onSurfaceVariant;
    } else if (isPositive) {
      icon = Icons.trending_up;
      color = Colors.orange;
    } else {
      icon = Icons.trending_down;
      color = Colors.green;
    }
    
    return Icon(
      icon,
      color: color,
      size: 16,
    );
  }

  Widget? _buildActions(BuildContext context) {
    if (onEdit == null && onDelete == null) return null;
    
    return PopupMenuButton<String>(
      onSelected: (value) {
        switch (value) {
          case 'edit':
            onEdit?.call();
            break;
          case 'delete':
            onDelete?.call();
            break;
        }
      },
      itemBuilder: (context) => [
        if (onEdit != null)
          const PopupMenuItem(
            value: 'edit',
            child: Row(
              children: [
                Icon(Icons.edit),
                SizedBox(width: 8),
                Text('Edit'),
              ],
            ),
          ),
        if (onDelete != null)
          const PopupMenuItem(
            value: 'delete',
            child: Row(
              children: [
                Icon(Icons.delete, color: Colors.red),
                SizedBox(width: 8),
                Text('Delete', style: TextStyle(color: Colors.red)),
              ],
            ),
          ),
      ],
    );
  }

  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);
    
    if (difference.inDays == 0) {
      // Today - show time
      final hour = dateTime.hour;
      final minute = dateTime.minute.toString().padLeft(2, '0');
      final amPm = hour >= 12 ? 'PM' : 'AM';
      final displayHour = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour);
      return 'Today at $displayHour:$minute $amPm';
    } else if (difference.inDays == 1) {
      return 'Yesterday';
    } else if (difference.inDays < 7) {
      // This week - show day of week
      final weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
      return weekdays[dateTime.weekday - 1];
    } else {
      // Older - show date
      final month = dateTime.month.toString().padLeft(2, '0');
      final day = dateTime.day.toString().padLeft(2, '0');
      return '$month/$day/${dateTime.year}';
    }
  }
}
