import SwiftUI
import UIKit

struct DataTypeRecordListView: View {
    let title: String
    let displayName: String
    let totalCount: Int
    let tint: Color

    @State private var viewModel: DataTypeRecordListViewModel?

    private let recordListMode: RecordListMode
    private let previewRecords: [HealthRecordValue]

    init(
        title: String,
        displayName: String,
        totalCount: Int,
        mode: RecordListMode,
        previewRecords: [HealthRecordValue] = [],
        tint: Color
    ) {
        self.title = title
        self.displayName = displayName
        self.totalCount = totalCount
        self.tint = tint
        self.recordListMode = mode
        self.previewRecords = previewRecords
    }


    private var isTruncated: Bool {
        guard let viewModel else { return totalCount > 0 }
        return viewModel.displayRecords.count < totalCount
    }

    var body: some View {
        Group {
            if let viewModel = viewModel {
                List {
                    Section {
                        DataTypeDetailRow(label: "Data Type") {
                            Text(displayName)
                                .foregroundStyle(.secondary)
                                .lineLimit(1)
                        }
                        DataTypeDetailRow(label: "Records") {
                            Text("\(totalCount)")
                                .foregroundStyle(tint)
                                .monospacedDigit()
                        }
                        if isTruncated {
                            HStack(spacing: 4) {
                                Image(systemName: "exclamationmark.circle.fill")
                                    .font(.caption)
                                    .foregroundStyle(Color.warningAmber)
                                Text("Showing \(viewModel.displayRecords.count) of \(totalCount)")
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                            }
                            .padding(.vertical, 4)
                        }
                        Text("HealthProbe stores timestamps, fingerprints, and metadata. Export includes complete record details.")
                            .font(.caption)
                            .foregroundStyle(.secondary)

                        if let preview = viewModel.exportPreview {
                            Divider()
                            DataTypeDetailRow(label: "Export Preview") {
                                Text("\(preview.estimatedRecordCount) JSON records")
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                                    .monospacedDigit()
                            }
                            DataTypeDetailRow(label: "Export Kind") {
                                Text(preview.exportKind)
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                                    .lineLimit(1)
                            }
                        } else if let error = viewModel.exportPreviewError {
                            Divider()
                            Label(error, systemImage: "exclamationmark.triangle.fill")
                                .font(.caption)
                                .foregroundStyle(Color.warningAmber)
                        }
                    }

                    if viewModel.displayRecords.isEmpty {
                        Section(title) {
                            Text("No records.")
                                .foregroundStyle(.secondary)
                        }
                    } else {
                        Section(title) {
                            ForEach(viewModel.displayRecords) { record in
                                HealthRecordValueRow(record: record, tint: tint)
                                    .onAppear {
                                        if record.id == viewModel.displayRecords.last?.id {
                                            Task { await viewModel.loadNextPage() }
                                        }
                                    }
                            }

                            if viewModel.isLoadingMore {
                                HStack(spacing: 8) {
                                    ProgressView()
                                        .scaleEffect(0.8)
                                    Text("Loading more...")
                                        .font(.caption)
                                        .foregroundStyle(.secondary)
                                }
                                .frame(maxWidth: .infinity, alignment: .center)
                                .padding(.vertical, 8)
                            }
                        }
                    }
                }
                .navigationTitle(title)
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .topBarTrailing) {
                        Menu {
                            Button(action: { Task { await viewModel.exportAllRecords() } }) {
                                if viewModel.exportState == .loading {
                                    Label("Exporting...", systemImage: "hourglass")
                                } else {
                                    Label("Export as JSON", systemImage: "square.and.arrow.up")
                                }
                            }
                            .disabled(viewModel.exportState == .loading)
                        } label: {
                            Image(systemName: "ellipsis.circle")
                                .foregroundStyle(.primary)
                        }
                    }
                }
                .onChange(of: viewModel.exportState) { _, newState in
                    if case .ready(let url) = newState {
                        shareExportURL(url)
                    }
                }
            } else {
                ProgressView()
                    .navigationTitle(title)
                    .navigationBarTitleDisplayMode(.inline)
            }
        }
        .task {
            guard viewModel == nil else { return }
            let vm = DataTypeRecordListViewModel(
                typeIdentifier: recordListMode.typeIdentifier,
                displayName: displayName,
                totalCount: totalCount,
                mode: recordListMode,
                previewRecords: previewRecords,
                archiveStore: SQLiteHealthArchiveStore.shared
            )
            viewModel = vm
            await vm.loadFirstPage()
        }
    }

    private func shareExportURL(_ url: URL) {
        let activity = UIActivityViewController(activityItems: [url], applicationActivities: nil)
        if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
            scene.windows.first?.rootViewController?.present(activity, animated: true)
        }
    }
}

private struct HealthRecordValueRow: View {
    let record: HealthRecordValue
    let tint: Color

    var body: some View {
        let recordDate = record.startDate.formatted(.dateTime.year().month().day())
        let startTime = record.startDate.formatted(.dateTime.hour().minute())
        let endTime = record.endDate.formatted(.dateTime.hour().minute())
        let timeRange = (startTime == endTime) ? startTime : "\(startTime)–\(endTime)"

        VStack(alignment: .leading, spacing: 6) {
            HStack(spacing: 12) {
                VStack(alignment: .leading, spacing: 2) {
                    Text("\(recordDate) • \(timeRange)")
                        .font(.subheadline.weight(.semibold))
                        .foregroundStyle(.primary)

                    if let displayValue = record.displayValue, !displayValue.isEmpty {
                        Text(displayValue)
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    } else {
                        Text("No value stored")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                }

                Spacer()

                Image(systemName: "xmark.circle.fill")
                    .font(.caption)
                    .foregroundStyle(Color.criticalRed)
            }

            Text(record.recordFingerprint.suffix(8))
                .font(.caption.monospaced())
                .foregroundStyle(.tertiary)
                .lineLimit(1)
        }
        .padding(.vertical, 2)
        .accessibilityElement(children: .combine)
    }
}

private struct DataTypeDetailRow<Content: View>: View {
    let label: String
    @ViewBuilder let content: () -> Content

    var body: some View {
        HStack {
            Text(label)
            Spacer()
            content()
        }
    }
}

#Preview {
    NavigationStack {
        DataTypeRecordListView(
            title: "Missing Records",
            displayName: "Step Count",
            totalCount: 1500,
            mode: .disappeared(typeIdentifier: "HKQuantityTypeIdentifierStepCount"),
            tint: .criticalRed
        )
    }
}
