import SwiftUI

/// Visual comparison of metric between current and previous snapshot
struct MetricComparisonCard: View {
    let currentValue: Int
    let previousValue: Int?
    let displayName: String
    let isCurrentValid: Bool
    let isPreviousTracked: Bool

    private var delta: Int {
        guard let prev = previousValue, currentValue >= 0, prev >= 0 else { return 0 }
        return currentValue - prev
    }

    private var deltaPercentage: Double {
        guard let prev = previousValue, prev > 0, currentValue >= 0 else { return 0 }
        return Double(delta) / Double(prev) * 100
    }

    private var deltaDirection: DeltaDirection {
        guard isPreviousTracked else { return .unknown }
        if delta > 0 { return .increase }
        if delta < 0 { return .decrease }
        return .stable
    }

    var body: some View {
        VStack(spacing: 16) {
            HStack(spacing: 24) {
                metricBox(
                    title: "Now",
                    value: currentValue,
                    isValid: isCurrentValid,
                    color: .accentColor
                )

                Divider()
                    .frame(height: 48)

                if isPreviousTracked, let prev = previousValue {
                    metricBox(
                        title: "Before",
                        value: prev,
                        isValid: prev >= 0,
                        color: .secondary
                    )
                } else {
                    VStack(alignment: .center, spacing: 8) {
                        Text("Before")
                            .font(.caption.weight(.medium))
                            .foregroundStyle(.secondary)
                        Text("–")
                            .font(.system(size: 24, weight: .semibold).monospacedDigit())
                            .foregroundStyle(.secondary)
                    }
                    .frame(maxWidth: .infinity)
                }
            }
            .padding(16)
            .background(Color(.systemBackground).opacity(0.5), in: RoundedRectangle(cornerRadius: 12))

            if isPreviousTracked {
                deltaIndicator
            }
        }
    }

    private func metricBox(title: String, value: Int, isValid: Bool, color: Color) -> some View {
        VStack(alignment: .center, spacing: 8) {
            Text(title)
                .font(.caption.weight(.medium))
                .foregroundStyle(.secondary)
            Text(isValid ? "\(value)" : "Unavailable")
                .font(.system(size: 24, weight: .semibold).monospacedDigit())
                .foregroundStyle(isValid ? color : .criticalRed)
                .lineLimit(1)
        }
        .frame(maxWidth: .infinity)
    }

    @ViewBuilder
    private var deltaIndicator: some View {
        HStack(spacing: 12) {
            switch deltaDirection {
            case .increase:
                Image(systemName: "arrow.up.right")
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundStyle(Color.healthyGreen)

            case .decrease:
                Image(systemName: "arrow.down.left")
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundStyle(Color.criticalRed)

            case .stable:
                Image(systemName: "minus")
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundStyle(.secondary)

            case .unknown:
                EmptyView()
            }

            VStack(alignment: .leading, spacing: 2) {
                Text(deltaLabel)
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(deltaLabelColor)

                if abs(deltaPercentage) > 0.1 {
                    Text(String(format: "%.1f%%", abs(deltaPercentage)))
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }

            Spacer()

            SeverityBadge(delta: delta)
        }
        .padding(12)
        .background(Color(.systemBackground).opacity(0.5), in: RoundedRectangle(cornerRadius: 8))
    }

    private var deltaLabel: String {
        guard delta != 0 else { return "No change" }
        return "\(delta > 0 ? "+" : "")\(delta) record\(delta == 1 || delta == -1 ? "" : "s")"
    }

    private var deltaLabelColor: Color {
        switch deltaDirection {
        case .increase: return .healthyGreen
        case .decrease: return .criticalRed
        case .stable, .unknown: return .primary
        }
    }
}

private enum DeltaDirection {
    case increase, decrease, stable, unknown
}

#Preview {
    VStack(spacing: 24) {
        MetricComparisonCard(
            currentValue: 1250,
            previousValue: 1180,
            displayName: "Step Count",
            isCurrentValid: true,
            isPreviousTracked: true
        )

        MetricComparisonCard(
            currentValue: 950,
            previousValue: 1100,
            displayName: "Heart Rate",
            isCurrentValid: true,
            isPreviousTracked: true
        )

        MetricComparisonCard(
            currentValue: 845,
            previousValue: nil,
            displayName: "Sleep",
            isCurrentValid: true,
            isPreviousTracked: false
        )
    }
    .padding()
}
