import SwiftUI

struct BookmarksView: View {
    @EnvironmentObject var userService: UserService
    @EnvironmentObject var contentService: ContentService
    
    @State private var isLoading: Bool = true
    @State private var posts: [Post] = []
    
    var body: some View {
        ZStack {
            ProgressView(label: {
                Text("Loading articles...")
                    .textStyle(.caption1)
            })
            .progressViewStyle(CircularProgressViewStyle())
            .opacity(isLoading ? 1 : 0)
            
            if posts.isEmpty {
                VStack {
                    ImageName.System.bookmarkRemove.image
                        .textStyle(.largeTitle, color: ColorName.text.color(variation: .tertiary))
                    
                    Text("You don't currently have any bookmarked articles.")
                        .textStyle(.body, color: ColorName.text.color(variation: .secondary))
                        .multilineTextAlignment(.center)
                        .padding()
                }
                .opacity(isLoading ? 0 : 1)
            } else {
                ScrollView {
                    PostListingView(posts: posts)
                }
                .opacity(isLoading ? 0 : 1)
            }
        }
        .navigationTitle("Bookmarks")
        .onChange(of: userService.userBookmarks, perform: { newValue in
            Task {
                let posts = try await contentService.postsForIDs(userService.userBookmarks)
                
                DispatchQueue.main.async {
                    self.posts = posts
                    isLoading = false
                }
            }
        })
        .onAppear {
            if userService.userBookmarks.isEmpty {
                isLoading = false
                return
            }
            
            Task {
                let posts = try await contentService.postsForIDs(userService.userBookmarks)
                
                DispatchQueue.main.async {
                    self.posts = posts
                    isLoading = false
                }
            }
        }
    }
}
