import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/constants/ui_constants.dart';
import '../../../core/providers/dynamic_theme_provider.dart';

/// Reusable card component for displaying entity data
/// Uses dynamic theme and provides consistent styling across all entities
class EntityCard extends StatelessWidget {
  final Map<String, dynamic> entity;
  final Function(Map<String, dynamic>) onEdit;
  final Function(Map<String, dynamic>) onDelete;
  final Function(Map<String, dynamic>)? onTap;
  final List<Map<String, dynamic>> displayFields;

  const EntityCard({
    super.key,
    required this.entity,
    required this.onEdit,
    required this.onDelete,
    this.onTap,
    this.displayFields = const [],
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<DynamicThemeProvider>(
      builder: (context, dynamicThemeProvider, child) {
        final colorScheme = dynamicThemeProvider.getCurrentColorScheme(
          Theme.of(context).brightness == Brightness.dark,
        );
        final size = MediaQuery.of(context).size;
        final isMobile = size.width < 600;
        final isTablet = size.width >= 600 && size.width < 1024;
        final double maxCardHeight = isMobile
            ? size.height * 0.34
            : isTablet
                ? size.height * 0.38
                : size.height * 0.42;
        final double horizontalPadding = isMobile
            ? UIConstants.spacing16
            : isTablet
                ? UIConstants.spacing20
                : UIConstants.spacing24;
        final double verticalPadding = isMobile
            ? UIConstants.spacing16
            : isTablet
                ? UIConstants.spacing16
                : UIConstants.spacing20;

        return ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: 160,
            maxHeight: maxCardHeight.clamp(160.0, size.height * 0.8),
          ),
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  colorScheme.surface,
                  colorScheme.surface.withOpacity(0.95),
                ],
              ),
              borderRadius: BorderRadius.circular(UIConstants.radius20),
              border: Border.all(
                color: colorScheme.primary.withOpacity(0.1),
                width: 1.5,
              ),
              boxShadow: [
                BoxShadow(
                  color: colorScheme.primary.withOpacity(0.08),
                  blurRadius: 20,
                  offset: const Offset(0, 8),
                  spreadRadius: 2,
                ),
              ],
            ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: onTap != null ? () => onTap!(entity) : null,
                borderRadius: BorderRadius.circular(UIConstants.radius20),
                child: Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: horizontalPadding,
                    vertical: verticalPadding,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Header with avatar and action buttons
                      Row(
                        children: [
                          _buildAvatar(colorScheme,
                              isMobile: isMobile, isTablet: isTablet),
                          const Spacer(),
                          _buildActionButtons(colorScheme),
                        ],
                      ),
                      const SizedBox(height: UIConstants.spacing16),

                      // Dynamic field display (scrollable to avoid overflow)
                      Expanded(
                        child: SingleChildScrollView(
                          padding: EdgeInsets.zero,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: _buildFieldDisplays(colorScheme),
                          ),
                        ),
                      ),
                      const SizedBox(height: UIConstants.spacing12),
                      // Status indicator pinned at bottom
                      _buildStatusIndicator(colorScheme),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildAvatar(ColorScheme colorScheme,
      {required bool isMobile, required bool isTablet}) {
    final double side = isMobile
        ? 44
        : isTablet
            ? 50
            : 56;
    final double icon = isMobile
        ? 20
        : isTablet
            ? 22
            : 24;
    return Container(
      width: side,
      height: side,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            colorScheme.primary,
            colorScheme.primary.withOpacity(0.8),
          ],
        ),
        borderRadius: BorderRadius.circular(UIConstants.radius12),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(0.3),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Icon(
        Icons.person_rounded,
        color: colorScheme.onPrimary,
        size: icon,
      ),
    );
  }

  Widget _buildActionButtons(ColorScheme colorScheme) {
    return Row(
      children: [
        // Edit Button
        Container(
          decoration: BoxDecoration(
            color: colorScheme.primaryContainer.withOpacity(0.3),
            borderRadius: BorderRadius.circular(UIConstants.radius8),
            border: Border.all(
              color: colorScheme.primary.withOpacity(0.2),
              width: 1,
            ),
          ),
          child: IconButton(
            onPressed: () => onEdit(entity),
            icon: Icon(
              Icons.edit_rounded,
              color: colorScheme.primary,
              size: 18,
            ),
            tooltip: 'Edit',
            padding: const EdgeInsets.all(8),
            constraints: const BoxConstraints(
              minWidth: 32,
              minHeight: 32,
            ),
          ),
        ),
        const SizedBox(width: UIConstants.spacing8),
        // Delete Button
        Container(
          decoration: BoxDecoration(
            color: colorScheme.errorContainer.withOpacity(0.3),
            borderRadius: BorderRadius.circular(UIConstants.radius8),
            border: Border.all(
              color: colorScheme.error.withOpacity(0.2),
              width: 1,
            ),
          ),
          child: IconButton(
            onPressed: () => onDelete(entity),
            icon: Icon(
              Icons.delete_rounded,
              color: colorScheme.error,
              size: 18,
            ),
            tooltip: 'Delete',
            padding: const EdgeInsets.all(8),
            constraints: const BoxConstraints(
              minWidth: 32,
              minHeight: 32,
            ),
          ),
        ),
      ],
    );
  }

  List<Widget> _buildFieldDisplays(ColorScheme colorScheme) {
    // Dynamic field display based on entity data
    final displayFields = _getDisplayFields();

    return displayFields.map((field) {
      final value = entity[field['key']]?.toString() ?? '';
      if (value.isEmpty) return const SizedBox.shrink();

      return Padding(
        padding: const EdgeInsets.only(bottom: UIConstants.spacing8),
        child: _buildFieldDisplay(field, value, colorScheme),
      );
    }).toList();
  }

  Widget _buildFieldDisplay(
      Map<String, dynamic> field, String value, ColorScheme colorScheme) {
    switch (field['type']) {
      case 'phone':
        return _buildPhoneDisplay(value, colorScheme);
      case 'email':
        return _buildEmailDisplay(value, colorScheme);
      case 'number':
        return _buildNumberDisplay(field['label'], value, colorScheme);
      default:
        return _buildTextDisplay(field['label'], value, colorScheme);
    }
  }

  Widget _buildPhoneDisplay(String value, ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: UIConstants.spacing12,
        vertical: UIConstants.spacing8,
      ),
      decoration: BoxDecoration(
        color: colorScheme.primaryContainer.withOpacity(0.2),
        borderRadius: BorderRadius.circular(UIConstants.radius8),
        border: Border.all(
          color: colorScheme.primary.withOpacity(0.1),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.phone_rounded,
            size: 16,
            color: colorScheme.primary,
          ),
          const SizedBox(width: UIConstants.spacing8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                color: colorScheme.onSurface.withOpacity(0.8),
                fontSize: 13,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmailDisplay(String value, ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: UIConstants.spacing12,
        vertical: UIConstants.spacing8,
      ),
      decoration: BoxDecoration(
        color: colorScheme.secondaryContainer.withOpacity(0.2),
        borderRadius: BorderRadius.circular(UIConstants.radius8),
        border: Border.all(
          color: colorScheme.secondary.withOpacity(0.1),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.email_rounded,
            size: 16,
            color: colorScheme.secondary,
          ),
          const SizedBox(width: UIConstants.spacing8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                color: colorScheme.onSurface.withOpacity(0.8),
                fontSize: 13,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTextDisplay(
      String label, String value, ColorScheme colorScheme) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          value,
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 16,
            fontWeight: FontWeight.w600,
            letterSpacing: 0.5,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        if (label.isNotEmpty) ...[
          const SizedBox(height: UIConstants.spacing4),
          Text(
            label,
            style: TextStyle(
              color: colorScheme.onSurface.withOpacity(0.7),
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ],
    );
  }

  Widget _buildNumberDisplay(
      String label, String value, ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: UIConstants.spacing12,
        vertical: UIConstants.spacing8,
      ),
      decoration: BoxDecoration(
        color: colorScheme.tertiaryContainer.withOpacity(0.2),
        borderRadius: BorderRadius.circular(UIConstants.radius8),
        border: Border.all(
          color: colorScheme.tertiary.withOpacity(0.1),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.numbers_rounded,
            size: 16,
            color: colorScheme.tertiary,
          ),
          const SizedBox(width: UIConstants.spacing8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                color: colorScheme.onSurface.withOpacity(0.8),
                fontSize: 13,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatusIndicator(ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: UIConstants.spacing8,
        vertical: UIConstants.spacing4,
      ),
      decoration: BoxDecoration(
        color: colorScheme.primary.withOpacity(0.1),
        borderRadius: BorderRadius.circular(UIConstants.radius12),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 6,
            height: 6,
            decoration: BoxDecoration(
              color: colorScheme.primary,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: UIConstants.spacing6),
          Text(
            'Active',
            style: TextStyle(
              color: colorScheme.primary,
              fontSize: 11,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  List<Map<String, dynamic>> _getDisplayFields() {
    // Use provided displayFields or default fields
    if (displayFields.isNotEmpty) {
      return displayFields;
    }

    // Default fields - try to get meaningful fields from entity
    final defaultFields = <Map<String, dynamic>>[];

    // Try to find primary fields
    final primaryFields = ['name', 'title', 'id'];
    for (final field in primaryFields) {
      if (entity.containsKey(field) && entity[field] != null) {
        defaultFields.add({'key': field, 'label': '', 'type': 'text'});
        break; // Only add first found primary field
      }
    }

    // Add other non-empty fields (max 3 for card display)
    int addedCount = 0;
    for (final entry in entity.entries) {
      if (entry.value != null &&
          entry.value.toString().isNotEmpty &&
          !primaryFields.contains(entry.key) &&
          addedCount < 2) {
        defaultFields.add({
          'key': entry.key,
          'label': _formatFieldLabel(entry.key),
          'type': _getFieldType(entry.value)
        });
        addedCount++;
      }
    }

    return defaultFields;
  }

  String _formatFieldLabel(String key) {
    return key
        .split('_')
        .map((word) => word[0].toUpperCase() + word.substring(1))
        .join(' ');
  }

  String _getFieldType(dynamic value) {
    if (value is num) return 'number';
    if (value.toString().contains('@')) return 'email';
    if (RegExp(r'^\+?[\d\s\-\(\)]+$').hasMatch(value.toString()))
      return 'phone';
    return 'text';
  }
}
