import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/providers/dynamic_theme_provider.dart';
import '../../../core/constants/ui_constants.dart';
import '../../../shared/widgets/app_bar/modern_app_bar.dart';
import '../../../shared/widgets/buttons/modern_button.dart';

/// Generic details component for displaying entity information
/// This component works with any entity type and provides consistent UI/UX
class EntityDetails extends StatefulWidget {
  final Map<String, dynamic> entity;
  final Function(Map<String, dynamic>) onEdit;
  final Function(Map<String, dynamic>) onDelete;
  final String title;
  final List<Map<String, dynamic>> displayFields;
  final bool isLoading;

  const EntityDetails({
    super.key,
    required this.entity,
    required this.onEdit,
    required this.onDelete,
    required this.title,
    this.displayFields = const [],
    this.isLoading = false,
  });

  @override
  State<EntityDetails> createState() => _EntityDetailsState();
}

class _EntityDetailsState extends State<EntityDetails>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
  }

  void _initializeAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
    ));

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.2, 1.0, curve: Curves.easeOutCubic),
    ));

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DynamicThemeProvider>(
      builder: (context, dynamicThemeProvider, child) {
        final colorScheme = dynamicThemeProvider.getCurrentColorScheme(
          Theme.of(context).brightness == Brightness.dark,
        );

        return Scaffold(
          backgroundColor: colorScheme.surface,
          appBar: ModernAppBar(
            title: widget.title,
            showBackButton: true,
            actions: [
              IconButton(
                onPressed: () => widget.onEdit(widget.entity),
                icon: Icon(
                  Icons.edit_rounded,
                  color: colorScheme.primary,
                ),
                tooltip: 'Edit',
              ),
              IconButton(
                onPressed: () => _showDeleteDialog(colorScheme),
                icon: Icon(
                  Icons.delete_rounded,
                  color: colorScheme.error,
                ),
                tooltip: 'Delete',
              ),
            ],
          ),
          body: widget.isLoading
              ? _buildLoadingState(colorScheme)
              : _buildContent(colorScheme),
        );
      },
    );
  }

  Widget _buildLoadingState(ColorScheme colorScheme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            color: colorScheme.primary,
            strokeWidth: 3,
          ),
          const SizedBox(height: UIConstants.spacing16),
          Text(
            'Loading details...',
            style: TextStyle(
              color: colorScheme.onSurface.withOpacity(0.7),
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildContent(ColorScheme colorScheme) {
    return SingleChildScrollView(
      padding: UIConstants.getResponsivePadding(
        context,
        mobile: UIConstants.screenPaddingMedium,
        tablet: UIConstants.screenPaddingLarge,
        desktop: UIConstants.screenPaddingLarge,
      ),
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return FadeTransition(
            opacity: _fadeAnimation,
            child: SlideTransition(
              position: _slideAnimation,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Header Card
                  _buildHeaderCard(colorScheme),

                  const SizedBox(height: UIConstants.spacing24),

                  // Details Section
                  _buildDetailsSection(colorScheme),

                  const SizedBox(height: UIConstants.spacing32),

                  // Action Buttons
                  _buildActionButtons(colorScheme),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildHeaderCard(ColorScheme colorScheme) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            colorScheme.primary,
            colorScheme.primary.withOpacity(0.8),
          ],
        ),
        borderRadius: BorderRadius.circular(UIConstants.radius20),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 10),
            spreadRadius: 2,
          ),
        ],
      ),
      child: Padding(
        padding: UIConstants.cardPaddingLarge,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Avatar and Title
            Row(
              children: [
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: colorScheme.onPrimary.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(UIConstants.radius16),
                  ),
                  child: Icon(
                    Icons.person_rounded,
                    color: colorScheme.onPrimary,
                    size: 30,
                  ),
                ),
                const SizedBox(width: UIConstants.spacing16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _getPrimaryFieldValue(),
                        style: TextStyle(
                          color: colorScheme.onPrimary,
                          fontSize: 24,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 0.5,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: UIConstants.spacing4),
                      Text(
                        widget.title,
                        style: TextStyle(
                          color: colorScheme.onPrimary.withOpacity(0.8),
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),

            const SizedBox(height: UIConstants.spacing16),

            // Status Badge
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: UIConstants.spacing12,
                vertical: UIConstants.spacing6,
              ),
              decoration: BoxDecoration(
                color: colorScheme.onPrimary.withOpacity(0.2),
                borderRadius: BorderRadius.circular(UIConstants.radius12),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                      color: colorScheme.onPrimary,
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: UIConstants.spacing8),
                  Text(
                    'Active',
                    style: TextStyle(
                      color: colorScheme.onPrimary,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailsSection(ColorScheme colorScheme) {
    final displayFields = widget.displayFields.isNotEmpty
        ? widget.displayFields
        : _getDefaultDisplayFields();

    return 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: Padding(
        padding: UIConstants.cardPaddingLarge,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Details',
              style: TextStyle(
                color: colorScheme.onSurface,
                fontSize: 20,
                fontWeight: FontWeight.w700,
                letterSpacing: 0.5,
              ),
            ),
            const SizedBox(height: UIConstants.spacing20),

            // Field Details
            ...displayFields
                .map((field) => _buildFieldDetail(field, colorScheme)),
          ],
        ),
      ),
    );
  }

  Widget _buildFieldDetail(
      Map<String, dynamic> field, ColorScheme colorScheme) {
    final value = widget.entity[field['key']]?.toString() ?? '';
    if (value.isEmpty) return const SizedBox.shrink();

    return Padding(
      padding: const EdgeInsets.only(bottom: UIConstants.spacing16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            field['label'] ?? field['key'],
            style: TextStyle(
              color: colorScheme.onSurface.withOpacity(0.7),
              fontSize: 12,
              fontWeight: FontWeight.w600,
              letterSpacing: 0.5,
            ),
          ),
          const SizedBox(height: UIConstants.spacing4),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(
              horizontal: UIConstants.spacing16,
              vertical: UIConstants.spacing12,
            ),
            decoration: BoxDecoration(
              color: _getFieldBackgroundColor(field['type'], colorScheme),
              borderRadius: BorderRadius.circular(UIConstants.radius12),
              border: Border.all(
                color: _getFieldBorderColor(field['type'], colorScheme),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Icon(
                  _getFieldIcon(field['type']),
                  size: 18,
                  color: _getFieldIconColor(field['type'], colorScheme),
                ),
                const SizedBox(width: UIConstants.spacing12),
                Expanded(
                  child: Text(
                    value,
                    style: TextStyle(
                      color: colorScheme.onSurface,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons(ColorScheme colorScheme) {
    return Row(
      children: [
        Expanded(
          child: ModernButton(
            text: 'Edit',
            type: ModernButtonType.secondary,
            size: ModernButtonSize.large,
            onPressed: () => widget.onEdit(widget.entity),
            icon: Icon(Icons.edit_rounded),
          ),
        ),
        const SizedBox(width: UIConstants.spacing16),
        Expanded(
          child: ModernButton(
            text: 'Delete',
            type: ModernButtonType.danger,
            size: ModernButtonSize.large,
            onPressed: () => _showDeleteDialog(colorScheme),
            icon: Icon(Icons.delete_rounded),
          ),
        ),
      ],
    );
  }

  void _showDeleteDialog(ColorScheme colorScheme) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: colorScheme.surface,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(UIConstants.radius20),
        ),
        title: Text(
          'Delete ${widget.title}',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontWeight: FontWeight.w700,
          ),
        ),
        content: Text(
          'Are you sure you want to delete this ${widget.title.toLowerCase()}? This action cannot be undone.',
          style: TextStyle(
            color: colorScheme.onSurface.withOpacity(0.8),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(
              'Cancel',
              style: TextStyle(
                color: colorScheme.onSurface.withOpacity(0.7),
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              widget.onDelete(widget.entity);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: colorScheme.error,
              foregroundColor: colorScheme.onError,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(UIConstants.radius12),
              ),
            ),
            child: const Text(
              'Delete',
              style: TextStyle(fontWeight: FontWeight.w600),
            ),
          ),
        ],
      ),
    );
  }

  String _getPrimaryFieldValue() {
    // Try to get the primary field value (usually 'name' or first field)
    final primaryFields = ['name', 'title', 'id'];
    for (final field in primaryFields) {
      final value = widget.entity[field]?.toString();
      if (value != null && value.isNotEmpty) {
        return value;
      }
    }

    // If no primary field found, return first non-empty field
    for (final entry in widget.entity.entries) {
      if (entry.value != null && entry.value.toString().isNotEmpty) {
        return entry.value.toString();
      }
    }

    return 'Unknown';
  }

  List<Map<String, dynamic>> _getDefaultDisplayFields() {
    return widget.entity.entries
        .where(
            (entry) => entry.value != null && entry.value.toString().isNotEmpty)
        .map((entry) => {
              'key': entry.key,
              'label': _formatFieldLabel(entry.key),
              'type': _getFieldType(entry.value),
            })
        .toList();
  }

  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';
  }

  Color _getFieldBackgroundColor(String type, ColorScheme colorScheme) {
    switch (type) {
      case 'phone':
        return colorScheme.primaryContainer.withOpacity(0.2);
      case 'email':
        return colorScheme.secondaryContainer.withOpacity(0.2);
      case 'number':
        return colorScheme.tertiaryContainer.withOpacity(0.2);
      default:
        return colorScheme.surfaceVariant.withOpacity(0.3);
    }
  }

  Color _getFieldBorderColor(String type, ColorScheme colorScheme) {
    switch (type) {
      case 'phone':
        return colorScheme.primary.withOpacity(0.1);
      case 'email':
        return colorScheme.secondary.withOpacity(0.1);
      case 'number':
        return colorScheme.tertiary.withOpacity(0.1);
      default:
        return colorScheme.outline.withOpacity(0.2);
    }
  }

  IconData _getFieldIcon(String type) {
    switch (type) {
      case 'phone':
        return Icons.phone_rounded;
      case 'email':
        return Icons.email_rounded;
      case 'number':
        return Icons.numbers_rounded;
      default:
        return Icons.text_fields_rounded;
    }
  }

  Color _getFieldIconColor(String type, ColorScheme colorScheme) {
    switch (type) {
      case 'phone':
        return colorScheme.primary;
      case 'email':
        return colorScheme.secondary;
      case 'number':
        return colorScheme.tertiary;
      default:
        return colorScheme.onSurface.withOpacity(0.7);
    }
  }
}
