import SwiftUI

/// Visual timeline showing how a data type's count evolved across snapshots
struct TypeEvolutionTimeline: View {
    let snapshots: [HealthSnapshot]
    let typeIdentifier: String
    let displayName: String
    let currentSnapshotID: UUID

    private var validDataPoints: [(snapshot: HealthSnapshot, count: Int)] {
        snapshots
            .compactMap { snapshot in
                guard let typeCount = snapshot.typeCounts?.first(where: { $0.typeIdentifier == typeIdentifier }),
                      !typeCount.isUnsupported,
                      typeCount.count >= 0 else {
                    return nil
                }
                return (snapshot, typeCount.count)
            }
            .sorted { $0.snapshot.timestamp < $1.snapshot.timestamp }
    }

    private var minCount: Int {
        validDataPoints.map(\.count).min() ?? 0
    }

    private var maxCount: Int {
        validDataPoints.map(\.count).max() ?? 1
    }

    private var countRange: Int {
        max(maxCount - minCount, 1)
    }

    var body: some View {
        if validDataPoints.count < 2 {
            return AnyView(EmptyView())
        }

        return AnyView(
            VStack(alignment: .leading, spacing: 8) {
                Text("Evolution")
                    .font(.headline.weight(.semibold))

                HStack(spacing: 4) {
                    ForEach(Array(validDataPoints.enumerated()), id: \.offset) { index, item in
                        timelinePoint(
                            snapshot: item.snapshot,
                            count: item.count,
                            index: index,
                            isLast: index == validDataPoints.count - 1
                        )

                        if index < validDataPoints.count - 1 {
                            timelineConnector(
                                from: validDataPoints[index].count,
                                to: validDataPoints[index + 1].count
                            )
                        }
                    }
                }

                compactStatsRow
            }
            .padding(16)
            .background(Color(.systemBackground).opacity(0.5), in: RoundedRectangle(cornerRadius: 12))
        )
    }

    private func timelinePoint(
        snapshot: HealthSnapshot,
        count: Int,
        index: Int,
        isLast: Bool
    ) -> some View {
        let normalizedHeight = CGFloat(count - minCount) / CGFloat(countRange)
        let isCurrentSnapshot = snapshot.id == currentSnapshotID
        let barHeight = 40 + normalizedHeight * 40

        return VStack(spacing: 8) {
            VStack(spacing: 0) {
                Spacer(minLength: 80 - barHeight)

                RoundedRectangle(cornerRadius: 4)
                    .fill(isCurrentSnapshot ? Color.accentColor : Color.secondary.opacity(0.6))
                    .frame(height: barHeight)

                Spacer(minLength: 0)
            }
            .frame(height: 80)

            Text("\(count)")
                .font(.caption.weight(.medium).monospacedDigit())
                .foregroundStyle(.secondary)

            Text(snapshot.timestamp, format: .dateTime.month().day())
                .font(.caption2)
                .foregroundStyle(.tertiary)
                .lineLimit(1)
        }
        .frame(maxWidth: .infinity)
    }

    private func timelineConnector(from: Int, to: Int) -> some View {
        let fromHeight = 40 + CGFloat(from - minCount) / CGFloat(countRange) * 40
        let toHeight = 40 + CGFloat(to - minCount) / CGFloat(countRange) * 40
        let heightDiff = abs(toHeight - fromHeight)

        let isIncreasing = to > from
        let percentChange = from > 0 ? Double(to - from) / Double(from) * 100 : 0
        let isSignificantIncrease = isIncreasing && percentChange > 10

        return VStack {
            Spacer()
                .frame(height: fromHeight)

            if isSignificantIncrease {
                HStack(spacing: 2) {
                    Spacer(minLength: 0)
                    Text("▲")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundStyle(Color.healthyGreen)
                    Spacer(minLength: 0)
                }
                .frame(height: heightDiff.isZero ? 1 : heightDiff)
            } else {
                Color.clear
                    .frame(height: heightDiff.isZero ? 1 : heightDiff)
            }

            Spacer()
        }
        .frame(height: 80)
    }

    private var compactStatsRow: some View {
        HStack(spacing: 16) {
            statItem(label: "Min", value: minCount)
            Divider()
            statItem(label: "Max", value: maxCount)
            Divider()
            if let latest = validDataPoints.last?.count {
                statItem(label: "Latest", value: latest)
            }
        }
        .font(.caption)
        .foregroundStyle(.secondary)
    }

    private func statItem(label: String, value: Int) -> some View {
        VStack(alignment: .center, spacing: 2) {
            Text(label)
                .font(.caption2.weight(.medium))
            Text("\(value)")
                .font(.caption.weight(.semibold).monospacedDigit())
                .foregroundStyle(.primary)
        }
        .frame(maxWidth: .infinity)
    }
}

#Preview {
    TypeEvolutionTimeline(
        snapshots: [
            HealthSnapshot(timestamp: Date.now.addingTimeInterval(-86400 * 5), osVersion: "iOS 26", deviceName: "iPhone", deviceID: "device1"),
            HealthSnapshot(timestamp: Date.now.addingTimeInterval(-86400 * 4), osVersion: "iOS 26", deviceName: "iPhone", deviceID: "device1"),
            HealthSnapshot(timestamp: Date.now.addingTimeInterval(-86400 * 3), osVersion: "iOS 26", deviceName: "iPhone", deviceID: "device1"),
            HealthSnapshot(timestamp: Date.now.addingTimeInterval(-86400 * 2), osVersion: "iOS 26", deviceName: "iPhone", deviceID: "device1"),
            HealthSnapshot(timestamp: Date.now.addingTimeInterval(-86400), osVersion: "iOS 26", deviceName: "iPhone", deviceID: "device1"),
            HealthSnapshot(timestamp: Date.now, osVersion: "iOS 26", deviceName: "iPhone", deviceID: "device1")
        ].map { snap in
            snap.typeCounts = [
                TypeCount(typeIdentifier: "HKQuantityTypeIdentifierStepCount", displayName: "Steps", count: Int.random(in: 800...1500))
            ]
            return snap
        },
        typeIdentifier: "HKQuantityTypeIdentifierStepCount",
        displayName: "Step Count",
        currentSnapshotID: UUID()
    )
    .padding()
}
