// ABOUTME: Data point popup widget for displaying detailed chart point information
// ABOUTME: Shows selected data point details with date, value, notes, and context actions

import 'package:flutter/material.dart';
import 'package:albi/services/chart_data_service.dart';
import 'package:albi/utils/constants.dart';
import 'package:intl/intl.dart';

/// Callback for data point actions
typedef OnDataPointAction = void Function(String action, ChartDataPoint dataPoint);

/// Widget that displays detailed information about a selected chart data point
class DataPointPopup extends StatelessWidget {
  final ChartDataPoint dataPoint;
  final String unit;
  final OnDataPointAction? onAction;
  final bool showActions;
  final VoidCallback? onClose;

  const DataPointPopup({
    super.key,
    required this.dataPoint,
    required this.unit,
    this.onAction,
    this.showActions = true,
    this.onClose,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 8,
      child: Container(
        constraints: const BoxConstraints(maxWidth: 300),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildHeader(context),
            _buildContent(context),
            if (showActions && dataPoint.entryId != null) 
              _buildActions(context),
          ],
        ),
      ),
    );
  }

  /// Build popup header with close button
  Widget _buildHeader(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(12),
          topRight: Radius.circular(12),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.place,
            size: 20,
            color: Theme.of(context).colorScheme.primary,
          ),
          const SizedBox(width: 8),
          Text(
            'Data Point',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              color: Theme.of(context).colorScheme.primary,
              fontWeight: FontWeight.w600,
            ),
          ),
          const Spacer(),
          if (onClose != null)
            IconButton(
              onPressed: onClose,
              icon: const Icon(Icons.close, size: 18),
              style: IconButton.styleFrom(
                foregroundColor: Theme.of(context).colorScheme.primary,
                padding: EdgeInsets.zero,
                minimumSize: const Size(24, 24),
              ),
            ),
        ],
      ),
    );
  }

  /// Build popup content with data point information
  Widget _buildContent(BuildContext context) {
    final dateFormat = DateFormat('EEEE, MMM d, yyyy');
    final timeFormat = DateFormat('h:mm a');
    final weightValue = _formatWeight(dataPoint.value, unit);

    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Weight value (main info)
          Row(
            children: [
              Icon(
                Icons.monitor_weight,
                size: 24,
                color: Theme.of(context).colorScheme.secondary,
              ),
              const SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Weight',
                    style: Theme.of(context).textTheme.labelMedium?.copyWith(
                      color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
                    ),
                  ),
                  Text(
                    '$weightValue $unit',
                    style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                      color: Theme.of(context).colorScheme.secondary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 16),
          
          // Date and time
          Row(
            children: [
              Icon(
                Icons.schedule,
                size: 20,
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      dateFormat.format(dataPoint.timestamp),
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    Text(
                      'at ${timeFormat.format(dataPoint.timestamp)}',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          // Notes (if available)
          if (dataPoint.notes != null && dataPoint.notes!.trim().isNotEmpty) ...[
            const SizedBox(height: 16),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(
                  Icons.note,
                  size: 20,
                  color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Notes',
                        style: Theme.of(context).textTheme.labelMedium?.copyWith(
                          color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
                        ),
                      ),
                      const SizedBox(height: 2),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Theme.of(context).colorScheme.surface,
                          borderRadius: BorderRadius.circular(6),
                          border: Border.all(
                            color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
                          ),
                        ),
                        child: Text(
                          dataPoint.notes!.trim(),
                          style: Theme.of(context).textTheme.bodySmall,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],

          // Additional context
          const SizedBox(height: 12),
          _buildContextInfo(context),
        ],
      ),
    );
  }

  /// Build context information about the data point
  Widget _buildContextInfo(BuildContext context) {
    final daysSinceNow = DateTime.now().difference(dataPoint.timestamp).inDays;
    final contextText = _getContextText(daysSinceNow);
    
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3),
        borderRadius: BorderRadius.circular(6),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info,
            size: 16,
            color: Theme.of(context).colorScheme.primary,
          ),
          const SizedBox(width: 6),
          Expanded(
            child: Text(
              contextText,
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                color: Theme.of(context).colorScheme.primary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build action buttons
  Widget _buildActions(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(12),
          bottomRight: Radius.circular(12),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextButton.icon(
              onPressed: () => onAction?.call('edit', dataPoint),
              icon: const Icon(Icons.edit, size: 16),
              label: const Text('Edit'),
              style: TextButton.styleFrom(
                foregroundColor: Theme.of(context).colorScheme.primary,
                textStyle: const TextStyle(fontSize: 12),
              ),
            ),
          ),
          Container(
            width: 1,
            height: 20,
            color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
          ),
          Expanded(
            child: TextButton.icon(
              onPressed: () => onAction?.call('delete', dataPoint),
              icon: const Icon(Icons.delete, size: 16),
              label: const Text('Delete'),
              style: TextButton.styleFrom(
                foregroundColor: Colors.red,
                textStyle: const TextStyle(fontSize: 12),
              ),
            ),
          ),
          Container(
            width: 1,
            height: 20,
            color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
          ),
          Expanded(
            child: TextButton.icon(
              onPressed: () => onAction?.call('details', dataPoint),
              icon: const Icon(Icons.info_outline, size: 16),
              label: const Text('Info'),
              style: TextButton.styleFrom(
                foregroundColor: Theme.of(context).colorScheme.secondary,
                textStyle: const TextStyle(fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Format weight value with appropriate decimal places
  String _formatWeight(double value, String unit) {
    final decimalPlaces = unit == UnitConstants.stonesUnit ? 2 : 1;
    return value.toStringAsFixed(decimalPlaces);
  }

  /// Get contextual text based on how long ago the measurement was taken
  String _getContextText(int daysSinceNow) {
    if (daysSinceNow == 0) {
      return 'Recorded today';
    } else if (daysSinceNow == 1) {
      return 'Recorded yesterday';
    } else if (daysSinceNow <= 7) {
      return 'Recorded $daysSinceNow days ago';
    } else if (daysSinceNow <= 30) {
      final weeks = (daysSinceNow / 7).round();
      return weeks == 1 
          ? 'Recorded 1 week ago' 
          : 'Recorded $weeks weeks ago';
    } else if (daysSinceNow <= 365) {
      final months = (daysSinceNow / 30).round();
      return months == 1 
          ? 'Recorded 1 month ago' 
          : 'Recorded $months months ago';
    } else {
      final years = (daysSinceNow / 365).round();
      return years == 1 
          ? 'Recorded 1 year ago' 
          : 'Recorded $years years ago';
    }
  }
}

/// Overlay widget for displaying the data point popup
class DataPointPopupOverlay extends StatelessWidget {
  final ChartDataPoint dataPoint;
  final String unit;
  final Offset position;
  final OnDataPointAction? onAction;
  final VoidCallback? onClose;

  const DataPointPopupOverlay({
    super.key,
    required this.dataPoint,
    required this.unit,
    required this.position,
    this.onAction,
    this.onClose,
  });

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final popupWidth = 300.0;
    final popupHeight = 250.0;

    // Calculate position to keep popup on screen
    double left = position.dx - popupWidth / 2;
    double top = position.dy - popupHeight - 20;

    // Adjust horizontal position
    if (left < 16) {
      left = 16;
    } else if (left + popupWidth > screenSize.width - 16) {
      left = screenSize.width - popupWidth - 16;
    }

    // Adjust vertical position
    if (top < 100) {
      top = position.dy + 20;
    }

    return Positioned(
      left: left,
      top: top,
      child: Material(
        color: Colors.transparent,
        child: DataPointPopup(
          dataPoint: dataPoint,
          unit: unit,
          onAction: onAction,
          onClose: onClose,
        ),
      ),
    );
  }
}
