import SwiftUI
import SwiftData

struct BookDetailView: View {
    @Environment(\.modelContext) private var modelContext
    @ObservedObject var viewModel: BookDetailViewModel

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                AsyncImage(url: viewModel.book.coverImageUrl) { phase in
                    if let image = phase.image {
                        image.resizable().scaledToFill()
                    } else {
                        RoundedRectangle(cornerRadius: 16).fill(.gray.opacity(0.2))
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 320)
                .clipShape(RoundedRectangle(cornerRadius: 16))

                Text(viewModel.book.title)
                    .font(.title.bold())
                Text(viewModel.book.authors.joined(separator: ", "))
                    .font(.headline)
                    .foregroundStyle(.secondary)

                if let year = viewModel.book.publishedYear {
                    Text("\(year)")
                        .font(.subheadline)
                }

                if !viewModel.book.categories.isEmpty {
                    Text(viewModel.book.categories.joined(separator: " • "))
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                }

                if let description = viewModel.book.description {
                    Text(description)
                        .font(.body)
                }

                PrimaryPillButton(
                    title: viewModel.isInLibrary ? String(localized: "detail.remove") : String(localized: "detail.add")
                ) {
                    viewModel.toggleLibrary(context: modelContext)
                }
                .padding(.top, 8)
            }
            .padding(20)
        }
        .background(Theme.background.ignoresSafeArea())
        .task {
            viewModel.refresh(context: modelContext)
        }
    }
}
