import SwiftUI

struct TopicPostsView: View {
    @EnvironmentObject var contentService: ContentService
    @EnvironmentObject var analyticsService: AnalyticsService
    
    var topic: Topic
    
    @State private var posts: [Post] = []
    
    var body: some View {
        ZStack {
            ColorName.background.color
                .ignoresSafeArea()
            
            if posts.isEmpty {
                ProgressView(label: {
                    Text("Loading articles...")
                        .textStyle(.caption1)
                }
                ).progressViewStyle(CircularProgressViewStyle())
            } else {
                ScrollViewWithBanner(banner: banner,
                                     onRefresh: refreshContent,
                                     onLoadMore: loadMoreContent) { _ in
                    PostListingView(posts: posts)
                }
            }
        }
        .overlay(
            BookmarksTipView()
        )
        .navigationTitle(topic.name)
        .onAppear {
            refreshContent()
            analyticsService.articleListWasViewed(listType: .topic(topicId: topic.id))
        }
    }
    
    private var banner: Banner? {
        contentService.bannerForPosition(ContentService.BannerPosition.topic(topicId: topic.id))
    }
    
    private func refreshContent() {
        Task {
            do {
                self.posts = try await contentService.postsForTopic(topic.id)
                self.pageToLoad = 2
            } catch {
                self.posts = []
            }
        }
    }
    
    @State private var pageToLoad: Int = 1
    @State private var isLoadingMore: Bool = false
    private func loadMoreContent() throws {
        
        Task {
            if isLoadingMore {
                return
            }
            isLoadingMore = true
            let posts = try await contentService.postsForTopic(topic.id, page: pageToLoad)
            DispatchQueue.main.async {
                self.posts = (self.posts + posts).unique()
                self.pageToLoad += 1
                isLoadingMore = false
            }
        }
    }
}
