import 'package:flutter/material.dart';
import '../create_post_screen.dart';
import '../../services/post_service.dart';
import '../../widgets/posts_list.dart';

class FeedPage extends StatefulWidget {
  @override
  _FeedPageState createState() => _FeedPageState();
}

class _FeedPageState extends State<FeedPage> {
  final GlobalKey<PostsListState> _postsListKey = GlobalKey<PostsListState>();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Feed', style: TextStyle(fontWeight: FontWeight.w600)),
        backgroundColor: Colors.white,
        foregroundColor: Color(0xFF6A4C93),
        elevation: 0,
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(1),
          child: Container(height: 1, color: Colors.grey[200]),
        ),
        automaticallyImplyLeading: false,
        actions: [
          IconButton(
            onPressed: () => _postsListKey.currentState?.refreshPosts(),
            icon: Icon(Icons.refresh),
            tooltip: 'Refresh',
          ),
        ],
      ),
      body: PostsList(
        key: _postsListKey,
        fetchPosts: PostService.getAllPosts,
        emptyStateTitle: 'Nothing here..',
        emptyStateSubtitle: 'Create the first post!',
        showRefreshIndicator: true,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _navigateToCreatePost,
        backgroundColor: Color(0xFF6A4C93),
        child: Icon(Icons.edit, color: Colors.white),
      ),
    );
  }


  Future<void> _navigateToCreatePost() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => CreatePostScreen()),
    );
    
    // If post was created successfully, refresh the feed
    if (result == true) {
      _postsListKey.currentState?.refreshPosts();
    }
  }
}

