import 'package:flutter/material.dart';

class ContentScreen extends StatefulWidget {
  final Color textColor;
  final Color cardColor;
  final Color primaryColor;

  const ContentScreen({
    super.key,
    required this.textColor,
    required this.cardColor,
    required this.primaryColor,
  });

  @override
  State<ContentScreen> createState() => _ContentScreenState();
}

class _ContentScreenState extends State<ContentScreen>
    with TickerProviderStateMixin {
  bool _isSearching = false;
  bool _showFilterOptions = false;
  bool _isGridView = true; // Track current view mode
  final TextEditingController _searchController = TextEditingController();
  late AnimationController _fabAnimationController;
  late AnimationController _filterAnimationController;

  final List<String> _filterOptions = [
    'All',
    'Words',
    'Grammar',
    'Stories',
    'Conversations',
    'Articles',
  ];

  final Map<String, bool> _selectedFilterOptions = {
    'All': true,
    'Words': false,
    'Grammar': false,
    'Stories': false,
    'Conversations': false,
    'Articles': false,
  };

  // Sample data for demonstration
  final List<Map<String, dynamic>> _contentItems = [
    {
      'title': 'English Vocabulary',
      'type': 'Words',
      'icon': Icons.text_fields,
      'itemCount': 45,
    },
    {
      'title': 'Grammar Basics',
      'type': 'Grammar',
      'icon': Icons.rule,
      'itemCount': 12,
    },
    {
      'title': 'Daily Conversations',
      'type': 'Conversations',
      'icon': Icons.chat,
      'itemCount': 23,
    },
    {
      'title': 'Short Stories',
      'type': 'Stories',
      'icon': Icons.book,
      'itemCount': 8,
    },
  ];

  @override
  void initState() {
    super.initState();
    _fabAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _filterAnimationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    _fabAnimationController.dispose();
    _filterAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: widget.cardColor,
      body: CustomScrollView(
        slivers: [
          _buildSliverAppBar(),
          if (_showFilterOptions) _buildFilterChips(),
          _buildBreadcrumb(),
          _buildContent(),
        ],
      ),
      floatingActionButton: _buildFloatingActionButtons(),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 120.0,
      floating: true,
      pinned: true,
      backgroundColor: widget.cardColor,
      elevation: 0,
      flexibleSpace: FlexibleSpaceBar(
        title: _isSearching
            ? null
            : Text(
                'Learning Content',
                style: TextStyle(
                  color: widget.textColor,
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                ),
              ),
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [widget.primaryColor.withOpacity(0.1), widget.cardColor],
            ),
          ),
        ),
      ),
      title: _isSearching
          ? Container(
              decoration: BoxDecoration(
                color: widget.textColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(25),
              ),
              child: TextField(
                controller: _searchController,
                style: TextStyle(color: widget.textColor),
                decoration: InputDecoration(
                  hintText: 'Search content...',
                  hintStyle: TextStyle(
                    color: widget.textColor.withOpacity(0.6),
                  ),
                  border: InputBorder.none,
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 12,
                  ),
                  prefixIcon: Icon(
                    Icons.search,
                    color: widget.textColor.withOpacity(0.6),
                  ),
                ),
                onChanged: (query) {
                  // TODO: Implement search logic
                },
              ),
            )
          : null,
      actions: [
        AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          child: IconButton(
            icon: Icon(
              _isSearching ? Icons.close : Icons.search,
              color: widget.textColor,
            ),
            onPressed: () {
              setState(() {
                _isSearching = !_isSearching;
                if (!_isSearching) {
                  _searchController.clear();
                }
              });
            },
          ),
        ),
        IconButton(
          icon: Icon(
            Icons.filter_list,
            color: _showFilterOptions ? widget.primaryColor : widget.textColor,
          ),
          onPressed: () {
            setState(() {
              _showFilterOptions = !_showFilterOptions;
              if (_showFilterOptions) {
                _filterAnimationController.forward();
              } else {
                _filterAnimationController.reverse();
              }
            });
          },
        ),
        PopupMenuButton<String>(
          icon: Icon(Icons.more_vert, color: widget.textColor),
          color: widget.cardColor,
          onSelected: (value) {
            switch (value) {
              case 'sync':
                _handleSync();
                break;
              case 'downloads':
                _handleDownloads();
                break;
            }
          },
          itemBuilder: (BuildContext context) => [
            PopupMenuItem(
              value: 'sync',
              child: Row(
                children: [
                  Icon(Icons.sync, color: widget.textColor),
                  const SizedBox(width: 8),
                  Text('Sync', style: TextStyle(color: widget.textColor)),
                ],
              ),
            ),
            PopupMenuItem(
              value: 'downloads',
              child: Row(
                children: [
                  Icon(Icons.download, color: widget.textColor),
                  const SizedBox(width: 8),
                  Text('Downloads', style: TextStyle(color: widget.textColor)),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildFilterChips() {
    return SliverToBoxAdapter(
      child: AnimatedBuilder(
        animation: _filterAnimationController,
        builder: (context, child) {
          return SlideTransition(
            position:
                Tween<Offset>(
                  begin: const Offset(0, -1),
                  end: Offset.zero,
                ).animate(
                  CurvedAnimation(
                    parent: _filterAnimationController,
                    curve: Curves.easeOut,
                  ),
                ),
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Filter by category',
                    style: TextStyle(
                      color: widget.textColor.withOpacity(0.7),
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 12),
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: _filterOptions.map((option) {
                        final isSelected = _selectedFilterOptions[option]!;
                        return Padding(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: FilterChip(
                            label: Text(
                              option,
                              style: TextStyle(
                                color: isSelected
                                    ? widget.cardColor
                                    : widget.textColor,
                                fontWeight: isSelected
                                    ? FontWeight.w600
                                    : FontWeight.normal,
                              ),
                            ),
                            selected: isSelected,
                            onSelected: (selected) =>
                                _updateFilter(option, selected),
                            backgroundColor: widget.textColor.withOpacity(0.1),
                            selectedColor: widget.primaryColor,
                            checkmarkColor: widget.cardColor,
                            elevation: isSelected ? 2 : 0,
                            pressElevation: 4,
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildBreadcrumb() {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Row(
          children: [
            Icon(
              Icons.folder_open,
              size: 16,
              color: widget.textColor.withOpacity(0.6),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                'Home > My Learning > Current Folder',
                style: TextStyle(
                  fontSize: 14,
                  color: widget.textColor.withOpacity(0.6),
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            IconButton(
              icon: Icon(
                _isGridView ? Icons.view_list : Icons.grid_view,
                color: widget.textColor.withOpacity(0.7),
              ),
              onPressed: () {
                setState(() {
                  _isGridView = !_isGridView;
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent() {
    if (_contentItems.isEmpty) {
      return _buildEmptyState();
    }

    return _isGridView ? _buildGridView() : _buildListView();
  }

  Widget _buildEmptyState() {
    return SliverFillRemaining(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: widget.primaryColor.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.library_books,
                size: 64,
                color: widget.primaryColor,
              ),
            ),
            const SizedBox(height: 24),
            Text(
              'Start Your Learning Journey',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: widget.textColor,
              ),
            ),
            const SizedBox(height: 12),
            Text(
              'Create your first learning content\nto get started!',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16,
                color: widget.textColor.withOpacity(0.7),
                height: 1.5,
              ),
            ),
            const SizedBox(height: 32),
            ElevatedButton.icon(
              onPressed: () => _showAddOptions(context),
              icon: const Icon(Icons.add),
              label: const Text('Create Content'),
              style: ElevatedButton.styleFrom(
                backgroundColor: widget.primaryColor,
                foregroundColor: widget.cardColor,
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 12,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildGridView() {
    return SliverPadding(
      padding: const EdgeInsets.all(16),
      sliver: SliverGrid(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.85,
          crossAxisSpacing: 16,
          mainAxisSpacing: 16,
        ),
        delegate: SliverChildBuilderDelegate(
          (context, index) => _buildContentCard(_contentItems[index]),
          childCount: _contentItems.length,
        ),
      ),
    );
  }

  Widget _buildContentCard(Map<String, dynamic> item) {
    return Card(
      elevation: 4,
      color: widget.cardColor,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: InkWell(
        onTap: () {
          // TODO: Navigate to content details
        },
        borderRadius: BorderRadius.circular(16),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: widget.primaryColor.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(
                      item['icon'],
                      color: widget.primaryColor,
                      size: 24,
                    ),
                  ),
                  PopupMenuButton(
                    icon: Icon(
                      Icons.more_vert,
                      color: widget.textColor.withOpacity(0.6),
                    ),
                    color: widget.cardColor,
                    itemBuilder: (context) => [
                      PopupMenuItem(
                        child: Text(
                          'Edit',
                          style: TextStyle(color: widget.textColor),
                        ),
                      ),
                      PopupMenuItem(
                        child: Text(
                          'Delete',
                          style: TextStyle(color: Colors.red),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Text(
                item['title'],
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: widget.textColor,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 8),
              Text(
                '${item['itemCount']} items',
                style: TextStyle(
                  fontSize: 14,
                  color: widget.textColor.withOpacity(0.6),
                ),
              ),
              const Spacer(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildListView() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) => _buildListItem(_contentItems[index]),
        childCount: _contentItems.length,
      ),
    );
  }

  Widget _buildListItem(Map<String, dynamic> item) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      elevation: 2,
      color: widget.cardColor,
      child: ListTile(
        leading: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: widget.primaryColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(item['icon'], color: widget.primaryColor),
        ),
        title: Text(
          item['title'],
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: widget.textColor,
          ),
        ),
        subtitle: Text(
          '${item['itemCount']} items',
          style: TextStyle(color: widget.textColor.withOpacity(0.6)),
        ),
        trailing: PopupMenuButton(
          icon: Icon(Icons.more_vert, color: widget.textColor.withOpacity(0.6)),
          color: widget.cardColor,
          itemBuilder: (context) => [
            PopupMenuItem(
              child: Text('Edit', style: TextStyle(color: widget.textColor)),
            ),
            PopupMenuItem(
              child: Text('Delete', style: TextStyle(color: Colors.red)),
            ),
          ],
        ),
        onTap: () {
          // TODO: Navigate to content details
        },
      ),
    );
  }

  Widget _buildFloatingActionButtons() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        FloatingActionButton(
          heroTag: 'add',
          onPressed: () => _showAddOptions(context),
          backgroundColor: widget.primaryColor,
          child: Icon(Icons.add, color: widget.cardColor),
        ),
      ],
    );
  }

  void _updateFilter(String option, bool selected) {
    setState(() {
      if (option == 'All') {
        _selectedFilterOptions.forEach((key, value) {
          _selectedFilterOptions[key] = selected;
        });
      } else {
        _selectedFilterOptions[option] = selected;
        if (!selected && _selectedFilterOptions['All']!) {
          _selectedFilterOptions['All'] = false;
        }
        if (selected &&
            _selectedFilterOptions.entries
                    .where((e) => e.key != 'All' && e.value)
                    .length ==
                _filterOptions.length - 1) {
          _selectedFilterOptions['All'] = true;
        }
      }
    });
  }

  void _handleSync() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('Syncing with Firebase...'),
        backgroundColor: widget.primaryColor,
      ),
    );
  }

  void _handleDownloads() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('Opening Downloads...'),
        backgroundColor: widget.primaryColor,
      ),
    );
  }

  void _showAddOptions(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        decoration: BoxDecoration(
          color: widget.cardColor,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.symmetric(vertical: 12),
              decoration: BoxDecoration(
                color: widget.textColor.withOpacity(0.3),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16),
              child: Text(
                'Create New Content',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: widget.textColor,
                ),
              ),
            ),
            ..._buildAddOptions(),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  List<Widget> _buildAddOptions() {
    final options = [
      {'title': 'Create Folder', 'icon': Icons.folder, 'color': Colors.orange},
      {'title': 'Word Card', 'icon': Icons.text_fields, 'color': Colors.blue},
      {'title': 'Story Card', 'icon': Icons.book, 'color': Colors.green},
      {'title': 'Conversation', 'icon': Icons.chat, 'color': Colors.purple},
      {'title': 'Grammar Card', 'icon': Icons.rule, 'color': Colors.red},
      {'title': 'Article Card', 'icon': Icons.article, 'color': Colors.teal},
    ];

    return options.map((option) {
      return ListTile(
        leading: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: (option['color'] as Color).withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            option['icon'] as IconData,
            color: option['color'] as Color,
          ),
        ),
        title: Text(
          option['title'] as String,
          style: TextStyle(
            color: widget.textColor,
            fontWeight: FontWeight.w500,
          ),
        ),
        onTap: () {
          Navigator.pop(context);
          if (option['title'] == 'Create Folder') {
            _showCreateFolderDialog(context);
          } else {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Creating ${option['title']}...')),
            );
          }
        },
      );
    }).toList();
  }

  void _showCreateFolderDialog(BuildContext context) {
    bool showAdvancedSettings = false;
    TextEditingController folderNameController = TextEditingController();
    Color selectedColor = Colors.blue;

    showDialog(
      context: context,
      builder: (dialogContext) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          backgroundColor: widget.cardColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: Text(
            'Create New Folder',
            style: TextStyle(
              color: widget.textColor,
              fontWeight: FontWeight.bold,
            ),
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: folderNameController,
                  decoration: InputDecoration(
                    labelText: 'Folder Name',
                    labelStyle: TextStyle(color: widget.primaryColor),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide(
                        color: widget.primaryColor,
                        width: 2,
                      ),
                    ),
                  ),
                  style: TextStyle(color: widget.textColor),
                ),
                const SizedBox(height: 16),
                InkWell(
                  onTap: () => setState(
                    () => showAdvancedSettings = !showAdvancedSettings,
                  ),
                  child: Row(
                    children: [
                      Icon(
                        showAdvancedSettings
                            ? Icons.keyboard_arrow_up
                            : Icons.keyboard_arrow_down,
                        color: widget.primaryColor,
                      ),
                      Text(
                        'Advanced Settings',
                        style: TextStyle(color: widget.primaryColor),
                      ),
                    ],
                  ),
                ),
                if (showAdvancedSettings) ...[
                  const SizedBox(height: 16),
                  DropdownButtonFormField<String>(
                    decoration: InputDecoration(
                      labelText: 'Location',
                      labelStyle: TextStyle(color: widget.primaryColor),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    items: const [
                      DropdownMenuItem(
                        value: 'root',
                        child: Text('Root Folder'),
                      ),
                      DropdownMenuItem(
                        value: 'folder1',
                        child: Text('Folder 1'),
                      ),
                      DropdownMenuItem(
                        value: 'folder2',
                        child: Text('Folder 2'),
                      ),
                    ],
                    onChanged: (value) {},
                    style: TextStyle(color: widget.textColor),
                    dropdownColor: widget.cardColor,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    'Folder Color',
                    style: TextStyle(color: widget.textColor),
                  ),
                  const SizedBox(height: 8),
                  Wrap(
                    spacing: 8,
                    children:
                        [
                              Colors.blue,
                              Colors.green,
                              Colors.red,
                              Colors.orange,
                              Colors.purple,
                              Colors.teal,
                            ]
                            .map(
                              (color) => GestureDetector(
                                onTap: () =>
                                    setState(() => selectedColor = color),
                                child: Container(
                                  width: 32,
                                  height: 32,
                                  decoration: BoxDecoration(
                                    color: color,
                                    shape: BoxShape.circle,
                                    border: selectedColor == color
                                        ? Border.all(
                                            color: widget.textColor,
                                            width: 2,
                                          )
                                        : null,
                                  ),
                                ),
                              ),
                            )
                            .toList(),
                  ),
                ],
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(dialogContext),
              child: Text(
                'Cancel',
                style: TextStyle(color: widget.primaryColor),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                // TODO: Implement folder creation
                Navigator.pop(dialogContext);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(
                      'Folder "${folderNameController.text}" created!',
                    ),
                  ),
                );
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: widget.primaryColor,
                foregroundColor: widget.cardColor,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('Create'),
            ),
          ],
        ),
      ),
    );
  }
}
improve ui