import SwiftUI
import SwiftData
import SharedModels

/// Lists downloaded YouTube videos with per-item deletion and total-size
/// summary (Issue #21, phase 4). Files live in the local (non-synced)
/// SwiftData container and the app's documents directory.
struct DownloadedVideosView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \DownloadedVideo.downloadedAt, order: .reverse)
    private var downloads: [DownloadedVideo]

    @State private var downloadService = VideoDownloadService.shared
    @State private var confirmDeleteAll = false

    private var totalBytes: Int {
        downloads.reduce(0) { $0 + $1.byteCount }
    }

    var body: some View {
        List {
            if downloads.isEmpty {
                Section {
                    ContentUnavailableView(
                        "No downloads",
                        systemImage: "arrow.down.to.line",
                        description: Text("Tap Download on any guide or grammar video to save it for offline viewing.")
                    )
                }
            } else {
                Section {
                    LabeledContent("Total size", value: sizeString(totalBytes))
                    if totalBytes > 500_000_000 {
                        Label("Downloads exceed 500 MB", systemImage: "exclamationmark.triangle")
                            .font(.caption)
                            .foregroundStyle(.orange)
                    }
                }

                Section("Videos") {
                    ForEach(downloads) { download in
                        VStack(alignment: .leading, spacing: 4) {
                            Text(download.title)
                                .font(.subheadline.weight(.medium))
                                .lineLimit(2)
                            HStack {
                                Text(sizeString(download.byteCount))
                                Text("·")
                                Text(download.downloadedAt.formatted(date: .abbreviated, time: .omitted))
                            }
                            .font(.caption)
                            .foregroundStyle(.secondary)
                        }
                        .swipeActions {
                            Button(role: .destructive) {
                                downloadService.delete(videoId: download.videoId, modelContext: modelContext)
                            } label: {
                                Label("Delete", systemImage: "trash")
                            }
                        }
                    }
                }

                Section {
                    Button(role: .destructive) {
                        confirmDeleteAll = true
                    } label: {
                        Label("Delete all downloads", systemImage: "trash")
                    }
                }
            }
        }
        .navigationTitle("Downloaded Videos")
        .navigationBarTitleDisplayMode(.inline)
        .confirmationDialog(
            "Delete all \(downloads.count) downloaded videos?",
            isPresented: $confirmDeleteAll,
            titleVisibility: .visible
        ) {
            Button("Delete All", role: .destructive) {
                for download in downloads {
                    downloadService.delete(videoId: download.videoId, modelContext: modelContext)
                }
            }
            Button("Cancel", role: .cancel) {}
        }
    }

    private func sizeString(_ bytes: Int) -> String {
        ByteCountFormatter.string(fromByteCount: Int64(bytes), countStyle: .file)
    }
}

#Preview {
    NavigationStack {
        DownloadedVideosView()
    }
    .modelContainer(for: DownloadedVideo.self, inMemory: true)
}
