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

/// Generic list component for displaying entities with search, pagination, and refresh
/// This component works with any entity type and provides consistent UI/UX
class EntityList extends StatefulWidget {
  final List<Map<String, dynamic>> entities;
  final bool isLoading;
  final String? errorMessage;
  final bool hasMoreData;
  final String searchQuery;
  final Function(String) onSearchChanged;
  final Function(Map<String, dynamic>) onEdit;
  final Function(Map<String, dynamic>) onDelete;
  final Function(Map<String, dynamic>)? onTap;
  final Function() onRefresh;
  final Function() onLoadMore;
  final String title;
  final Function()? onAddNew;
  final List<Map<String, dynamic>> displayFields;

  const EntityList({
    super.key,
    required this.entities,
    required this.isLoading,
    this.errorMessage,
    required this.hasMoreData,
    required this.searchQuery,
    required this.onSearchChanged,
    required this.onEdit,
    required this.onDelete,
    this.onTap,
    required this.onRefresh,
    required this.onLoadMore,
    required this.title,
    this.onAddNew,
    this.displayFields = const [],
  });

  @override
  State<EntityList> createState() => _EntityListState();
}

class _EntityListState extends State<EntityList> with TickerProviderStateMixin {
  late AnimationController _animationController;
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _searchController.text = widget.searchQuery;
    _scrollController.addListener(_scrollListener);
  }

  void _initializeAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _animationController.forward();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      if (widget.hasMoreData && !widget.isLoading) {
        widget.onLoadMore();
      }
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    _searchController.dispose();
    _scrollController.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: [
              if (widget.onAddNew != null)
                IconButton(
                  onPressed: widget.onAddNew,
                  icon: Icon(
                    Icons.add_rounded,
                    color: colorScheme.primary,
                  ),
                  tooltip: 'Add New',
                ),
            ],
          ),
          body: Column(
            children: [
              // Search Bar
              _buildSearchBar(colorScheme),

              // Content
              Expanded(
                child: _buildContent(colorScheme),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSearchBar(ColorScheme colorScheme) {
    return Container(
      margin: UIConstants.getResponsivePadding(
        context,
        mobile: UIConstants.screenPaddingMedium,
        tablet: UIConstants.screenPaddingLarge,
        desktop: UIConstants.screenPaddingLarge,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            colorScheme.surface,
            colorScheme.surface.withOpacity(0.95),
          ],
        ),
        borderRadius: BorderRadius.circular(UIConstants.radius16),
        border: Border.all(
          color: colorScheme.primary.withOpacity(0.1),
          width: 1.5,
        ),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(0.08),
            blurRadius: 15,
            offset: const Offset(0, 5),
            spreadRadius: 1,
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _searchController,
              onChanged: widget.onSearchChanged,
              style: TextStyle(
                color: colorScheme.onSurface,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
              decoration: InputDecoration(
                hintText: 'Search ${widget.title.toLowerCase()}...',
                hintStyle: TextStyle(
                  color: colorScheme.onSurface.withOpacity(0.6),
                  fontSize: 16,
                  fontWeight: FontWeight.w400,
                ),
                prefixIcon: Icon(
                  Icons.search_rounded,
                  color: colorScheme.primary,
                  size: 22,
                ),
                suffixIcon: _searchController.text.isNotEmpty
                    ? IconButton(
                        onPressed: () {
                          _searchController.clear();
                          widget.onSearchChanged('');
                        },
                        icon: Icon(
                          Icons.clear_rounded,
                          color: colorScheme.onSurface.withOpacity(0.6),
                          size: 20,
                        ),
                      )
                    : null,
                border: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: UIConstants.spacing16,
                  vertical: UIConstants.spacing12,
                ),
              ),
            ),
          ),
          IconButton(
            onPressed: widget.onRefresh,
            icon: Icon(
              Icons.refresh_rounded,
              color: colorScheme.onSurface.withOpacity(0.8),
              size: 22,
            ),
            tooltip: 'Refresh',
          ),
        ],
      ),
    );
  }

  Widget _buildContent(ColorScheme colorScheme) {
    if (widget.isLoading && widget.entities.isEmpty) {
      return _buildLoadingState(colorScheme);
    }

    if (widget.errorMessage != null && widget.entities.isEmpty) {
      return _buildErrorState(colorScheme);
    }

    if (widget.entities.isEmpty) {
      return _buildEmptyState(colorScheme);
    }

    return _buildEntityGrid(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 ${widget.title.toLowerCase()}...',
            style: TextStyle(
              color: colorScheme.onSurface.withOpacity(0.7),
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorState(ColorScheme colorScheme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: colorScheme.errorContainer.withOpacity(0.2),
              borderRadius: BorderRadius.circular(UIConstants.radius20),
            ),
            child: Icon(
              Icons.error_outline_rounded,
              color: colorScheme.error,
              size: 40,
            ),
          ),
          const SizedBox(height: UIConstants.spacing16),
          Text(
            'Error Loading Data',
            style: TextStyle(
              color: colorScheme.onSurface,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: UIConstants.spacing8),
          Text(
            widget.errorMessage ?? 'Something went wrong',
            style: TextStyle(
              color: colorScheme.onSurface.withOpacity(0.7),
              fontSize: 14,
              fontWeight: FontWeight.w400,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: UIConstants.spacing24),
          ElevatedButton.icon(
            onPressed: widget.onRefresh,
            icon: Icon(
              Icons.refresh_rounded,
              color: colorScheme.onPrimary,
            ),
            label: Text(
              'Retry',
              style: TextStyle(
                color: colorScheme.onPrimary,
                fontWeight: FontWeight.w600,
              ),
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: colorScheme.primary,
              foregroundColor: colorScheme.onPrimary,
              elevation: 4,
              shadowColor: colorScheme.primary.withOpacity(0.3),
              padding: const EdgeInsets.symmetric(
                horizontal: UIConstants.spacing24,
                vertical: UIConstants.spacing12,
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(UIConstants.radius12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState(ColorScheme colorScheme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: colorScheme.primaryContainer.withOpacity(0.2),
              borderRadius: BorderRadius.circular(UIConstants.radius20),
            ),
            child: Icon(
              Icons.inbox_outlined,
              color: colorScheme.primary,
              size: 40,
            ),
          ),
          const SizedBox(height: UIConstants.spacing16),
          Text(
            'No ${widget.title.toLowerCase()} found',
            style: TextStyle(
              color: colorScheme.onSurface,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: UIConstants.spacing8),
          Text(
            widget.searchQuery.isNotEmpty
                ? 'Try adjusting your search terms'
                : 'Start by adding your first ${widget.title.toLowerCase()}',
            style: TextStyle(
              color: colorScheme.onSurface.withOpacity(0.7),
              fontSize: 14,
              fontWeight: FontWeight.w400,
            ),
            textAlign: TextAlign.center,
          ),
          if (widget.onAddNew != null) ...[
            const SizedBox(height: UIConstants.spacing24),
            ElevatedButton.icon(
              onPressed: widget.onAddNew,
              icon: Icon(
                Icons.add_rounded,
                color: colorScheme.onPrimary,
              ),
              label: Text(
                'Add ${widget.title}',
                style: TextStyle(
                  color: colorScheme.onPrimary,
                  fontWeight: FontWeight.w600,
                ),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.onPrimary,
                elevation: 4,
                shadowColor: colorScheme.primary.withOpacity(0.3),
                padding: const EdgeInsets.symmetric(
                  horizontal: UIConstants.spacing24,
                  vertical: UIConstants.spacing12,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(UIConstants.radius12),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildEntityGrid(ColorScheme colorScheme) {
    return RefreshIndicator(
      onRefresh: () async => widget.onRefresh(),
      color: colorScheme.primary,
      child: GridView.builder(
        controller: _scrollController,
        padding: UIConstants.getResponsivePadding(
          context,
          mobile: UIConstants.screenPaddingMedium,
          tablet: UIConstants.screenPaddingLarge,
          desktop: UIConstants.screenPaddingLarge,
        ),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: UIConstants.getResponsiveInt(
            context,
            mobile: 1,
            tablet: 2,
            desktop: 3,
          ),
          childAspectRatio: 0.85,
          crossAxisSpacing: UIConstants.spacing16,
          mainAxisSpacing: UIConstants.spacing16,
        ),
        itemCount: widget.entities.length + (widget.isLoading ? 1 : 0),
        itemBuilder: (context, index) {
          if (index < widget.entities.length) {
            return AnimatedBuilder(
              animation: _animationController,
              builder: (context, child) {
                return FadeTransition(
                  opacity: _animationController,
                  child: Transform.translate(
                    offset: Offset(0, 20 * (1 - _animationController.value)),
                    child: EntityCard(
                      entity: widget.entities[index],
                      onEdit: widget.onEdit,
                      onDelete: widget.onDelete,
                      onTap: widget.onTap,
                      displayFields: widget.displayFields,
                    ),
                  ),
                );
              },
            );
          } else {
            return _buildLoadingCard(colorScheme);
          }
        },
      ),
    );
  }

  Widget _buildLoadingCard(ColorScheme colorScheme) {
    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,
        ),
      ),
      child: Center(
        child: CircularProgressIndicator(
          color: colorScheme.primary,
          strokeWidth: 2,
        ),
      ),
    );
  }
}
