import SwiftUI

struct SnapshotProgressSheet: View {
    @Bindable var viewModel: DashboardViewModel
    @State private var selectedTab: Tab = .progress

    enum Tab { case progress, report }

    var body: some View {
        NavigationStack {
            VStack(spacing: 12) {
                // Header
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Health data snapshot")
                            .font(.headline)
                        Text("\(viewModel.fetchProgress.count) metrics")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                    Spacer()
                    Image(systemName: statusIcon)
                        .font(.title3)
                        .foregroundStyle(statusColor)
                }
                .padding(.horizontal)

                // Tab picker
                Picker("View", selection: $selectedTab) {
                    Text("Progress").tag(Tab.progress)
                    Text("Report").tag(Tab.report)
                }
                .pickerStyle(.segmented)
                .padding(.horizontal)

                // Content
                Group {
                    switch selectedTab {
                    case .progress:
                        ProgressTabView(entries: viewModel.fetchProgress, isComplete: !viewModel.isCreatingSnapshot)
                    case .report:
                        ReportTabView(entries: viewModel.fetchProgress, duration: duration)
                    }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
            }
            .padding(.vertical, 12)
        }
    }

    private var statusIcon: String {
        let unauthorized = viewModel.fetchProgress.filter { if case .unauthorized = $0.status { return true }; return false }
        let failed = viewModel.fetchProgress.filter { if case .failed = $0.status { return true }; return false }

        if viewModel.isCreatingSnapshot {
            return "hourglass.circle"
        } else if unauthorized.isEmpty && failed.isEmpty {
            return "checkmark.circle.fill"
        } else {
            return "exclamationmark.circle.fill"
        }
    }

    private var statusColor: Color {
        let unauthorized = viewModel.fetchProgress.filter { if case .unauthorized = $0.status { return true }; return false }
        let failed = viewModel.fetchProgress.filter { if case .failed = $0.status { return true }; return false }

        if viewModel.isCreatingSnapshot {
            return .blue
        } else if unauthorized.isEmpty && failed.isEmpty {
            return Color.healthyGreen
        } else if unauthorized.isEmpty {
            return Color.criticalRed
        } else {
            return Color.warningAmber
        }
    }

    private var duration: TimeInterval? {
        guard let start = viewModel.fetchStartTime else { return nil }
        return Date().timeIntervalSince(start)
    }
}

// MARK: - Progress Tab
private struct ProgressTabView: View {
    let entries: [TypeProgressEntry]
    let isComplete: Bool

    var body: some View {
        List {
            ForEach(entries) { entry in
                HStack(spacing: 12) {
                    icon(for: entry.status)
                        .frame(width: 20)

                    VStack(alignment: .leading, spacing: 2) {
                        Text(entry.displayName)
                            .font(.subheadline)
                        statusText(for: entry.status)
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }

                    Spacer()
                }
                .padding(.vertical, 4)
            }
        }
        .listStyle(.plain)
    }

    private func icon(for status: TypeProgressEntry.Status) -> some View {
        Group {
            switch status {
            case .pending:
                Image(systemName: "circle")
                    .foregroundStyle(.gray)
            case .complete:
                Image(systemName: "checkmark.circle.fill")
                    .foregroundStyle(Color.healthyGreen)
            case .unauthorized:
                Image(systemName: "exclamationmark.triangle.fill")
                    .foregroundStyle(Color.warningAmber)
            case .failed:
                Image(systemName: "xmark.circle.fill")
                    .foregroundStyle(Color.criticalRed)
            }
        }
    }

    private func statusText(for status: TypeProgressEntry.Status) -> some View {
        Group {
            switch status {
            case .pending:
                Text("Pending")
            case .complete(let count):
                Text("\(count) records")
            case .unauthorized:
                Text("Not authorized")
            case .failed(let reason):
                Text(reason)
            }
        }
    }
}

// MARK: - Report Tab
private struct ReportTabView: View {
    let entries: [TypeProgressEntry]
    let duration: TimeInterval?

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                // Summary
                VStack(alignment: .leading, spacing: 8) {
                    Text("SUMMARY")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(.secondary)

                    let successful = entries.filter { if case .complete = $0.status { return true }; return false }
                    let unauthorized = entries.filter { if case .unauthorized = $0.status { return true }; return false }
                    let failed = entries.filter { if case .failed = $0.status { return true }; return false }

                    HStack {
                        Text("Successful: \(successful.count)")
                        Spacer()
                        Text("\(successful.count)")
                            .fontWeight(.semibold)
                            .foregroundStyle(Color.healthyGreen)
                    }
                    .font(.caption)

                    if !unauthorized.isEmpty {
                        HStack {
                            Text("Not authorized: \(unauthorized.count)")
                            Spacer()
                            Text("\(unauthorized.count)")
                                .fontWeight(.semibold)
                                .foregroundStyle(Color.warningAmber)
                        }
                        .font(.caption)
                    }

                    if !failed.isEmpty {
                        HStack {
                            Text("Failed: \(failed.count)")
                            Spacer()
                            Text("\(failed.count)")
                                .fontWeight(.semibold)
                                .foregroundStyle(Color.criticalRed)
                        }
                        .font(.caption)
                    }

                    if let duration {
                        HStack {
                            Text("Duration:")
                            Spacer()
                            Text(formatDuration(duration))
                                .fontWeight(.semibold)
                                .foregroundStyle(.secondary)
                        }
                        .font(.caption)
                    }
                }
                .padding(12)
                .background(Color(.systemGray6))
                .cornerRadius(8)

                // Unauthorized metrics advice
                let unauthorized = entries.filter { if case .unauthorized = $0.status { return true }; return false }
                if !unauthorized.isEmpty {
                    VStack(alignment: .leading, spacing: 8) {
                        Label("Permission required", systemImage: "exclamationmark.circle.fill")
                            .font(.subheadline.weight(.semibold))
                            .foregroundStyle(Color.warningAmber)

                        Text("\(unauthorized.count) metric\(unauthorized.count == 1 ? "" : "s") excluded — enable in Health app")
                            .font(.caption)
                            .foregroundStyle(.secondary)

                        VStack(alignment: .leading, spacing: 8) {
                            ForEach(unauthorized) { entry in
                                VStack(alignment: .leading, spacing: 4) {
                                    Text(entry.displayName)
                                        .font(.caption.weight(.semibold))
                                    Text("Health app → Settings → Privacy → Health → HealthProbe")
                                        .font(.caption2)
                                        .foregroundStyle(.secondary)
                                }
                                .padding(8)
                                .background(Color(.systemGray6))
                                .cornerRadius(6)
                            }
                        }
                    }
                }

                // Failed metrics
                let failed = entries.filter { if case .failed = $0.status { return true }; return false }
                if !failed.isEmpty {
                    VStack(alignment: .leading, spacing: 8) {
                        Label("Errors", systemImage: "xmark.circle.fill")
                            .font(.subheadline.weight(.semibold))
                            .foregroundStyle(Color.criticalRed)

                        VStack(alignment: .leading, spacing: 8) {
                            ForEach(failed) { entry in
                                VStack(alignment: .leading, spacing: 2) {
                                    Text(entry.displayName)
                                        .font(.caption.weight(.semibold))
                                    if case .failed(let reason) = entry.status {
                                        Text(reason)
                                            .font(.caption2)
                                            .foregroundStyle(.secondary)
                                    }
                                }
                                .padding(8)
                                .background(Color(.systemGray6))
                                .cornerRadius(6)
                            }
                        }
                    }
                }

                // All metrics list
                VStack(alignment: .leading, spacing: 8) {
                    Text("ALL METRICS")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(.secondary)

                    VStack(spacing: 6) {
                        ForEach(entries.sorted { $0.displayName < $1.displayName }) { entry in
                            HStack(spacing: 8) {
                                icon(for: entry.status)
                                    .frame(width: 14)

                                Text(entry.displayName)
                                    .font(.caption)

                                Spacer()

                                statusLabel(for: entry.status)
                                    .font(.caption2)
                                    .foregroundStyle(.secondary)
                            }
                            .padding(.vertical, 6)
                            .padding(.horizontal, 10)
                            .background(Color(.systemGray6))
                            .cornerRadius(6)
                        }
                    }
                }
            }
            .padding(12)
        }
    }

    private func icon(for status: TypeProgressEntry.Status) -> some View {
        Group {
            switch status {
            case .complete:
                Image(systemName: "checkmark.circle.fill")
                    .foregroundStyle(Color.healthyGreen)
            case .unauthorized:
                Image(systemName: "exclamationmark.triangle.fill")
                    .foregroundStyle(Color.warningAmber)
            case .failed:
                Image(systemName: "xmark.circle.fill")
                    .foregroundStyle(Color.criticalRed)
            case .pending:
                Image(systemName: "circle")
                    .foregroundStyle(.gray)
            }
        }
    }

    private func statusLabel(for status: TypeProgressEntry.Status) -> some View {
        Group {
            switch status {
            case .complete(let count):
                Text("\(count) records")
            case .unauthorized:
                Text("Not authorized")
            case .failed(let reason):
                Text(reason)
            case .pending:
                Text("Pending")
            }
        }
    }

    private func formatDuration(_ seconds: TimeInterval) -> String {
        if seconds < 60 {
            return String(format: "%.1fs", seconds)
        } else {
            let minutes = Int(seconds) / 60
            let secs = Int(seconds) % 60
            return String(format: "%dm %ds", minutes, secs)
        }
    }
}

#Preview {
    @Previewable @State var viewModel = DashboardViewModel()

    SnapshotProgressSheet(viewModel: viewModel)
        .onAppear {
            viewModel.fetchProgress = [
                TypeProgressEntry(id: "steps", displayName: "Steps", status: .complete(1234)),
                TypeProgressEntry(id: "activeEnergy", displayName: "Active Energy", status: .unauthorized),
                TypeProgressEntry(id: "heartRate", displayName: "Heart Rate", status: .complete(5678)),
                TypeProgressEntry(id: "sleep", displayName: "Sleep", status: .failed("Timeout")),
            ]
        }
}
