//
//  StatsHealthSection.swift
//  lichunWebsocket
//
//  Stats & Health section with core stats, physical info, conditions, habits
//

import SwiftUI

struct StatsHealthSection: View {
    @ObservedObject var person: Person

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.lg) {
            // Core stats grid
            coreStatsSection

            // Physical info
            physicalInfoSection

            // Health conditions (if any)
            if hasHealthConditions {
                healthConditionsSection
            }

            // Habits (if any)
            if !person.habits.isEmpty {
                habitsSection
            }
        }
    }

    // MARK: - Core Stats Section

    private var coreStatsSection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.md) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "chart.bar.fill")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(AppColors.primary)

                Text("Core Stats")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            VStack(spacing: AppSpacing.sm) {
                CozyStatBar(
                    label: "Health",
                    value: Int(person.health),
                    color: AppColors.health,
                    showPercentage: true
                )

                CozyStatBar(
                    label: "Happiness",
                    value: person.happiness,
                    color: AppColors.happiness,
                    showPercentage: true
                )

                CozyStatBar(
                    label: "Intelligence",
                    value: person.intelligence,
                    color: AppColors.intelligence,
                    showPercentage: true
                )

                CozyStatBar(
                    label: "Prestige",
                    value: person.prestige,
                    color: AppColors.prestige,
                    showPercentage: true
                )

                CozyStatBar(
                    label: "Energy",
                    value: person.calcEnergy,
                    color: AppColors.energy,
                    showPercentage: true
                )
            }
        }
    }

    // MARK: - Physical Info Section

    private var physicalInfoSection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "figure.stand")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(Color.blue)

                Text("Physical")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            LazyVGrid(columns: [
                GridItem(.flexible()),
                GridItem(.flexible())
            ], spacing: AppSpacing.sm) {
                PhysicalInfoCard(
                    icon: "calendar",
                    label: "Age",
                    value: "\(person.ageYears) years"
                )

                PhysicalInfoCard(
                    icon: "person.fill",
                    label: "Sex",
                    value: person.sex
                )

                PhysicalInfoCard(
                    icon: "face.smiling",
                    label: "Mood",
                    value: person.mood.isEmpty ? "Neutral" : person.mood
                )

                PhysicalInfoCard(
                    icon: "heart.text.square",
                    label: "Status",
                    value: person.status.isEmpty ? "Active" : person.status.capitalized
                )
            }
        }
    }

    // MARK: - Health Conditions Section

    private var hasHealthConditions: Bool {
        // Check for various health indicators
        Int(person.health) < 50
    }

    private var healthConditionsSection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "cross.case.fill")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(Color.red)

                Text("Health Conditions")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            VStack(spacing: AppSpacing.xs) {
                if Int(person.health) < 30 {
                    ConditionTag(name: "Poor Health", severity: .critical)
                } else if Int(person.health) < 50 {
                    ConditionTag(name: "Fair Health", severity: .warning)
                }
            }
        }
    }

    // MARK: - Habits Section

    private var habitsSection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "arrow.triangle.2.circlepath")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(Color.orange)

                Text("Habits")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            VStack(spacing: AppSpacing.xs) {
                ForEach(person.habits, id: \.name) { habit in
                    ProfileHabitRow(habit: habit)
                }
            }
        }
    }
}

// MARK: - Physical Info Card

private struct PhysicalInfoCard: View {
    let icon: String
    let label: String
    let value: String

    var body: some View {
        HStack(spacing: AppSpacing.sm) {
            Image(systemName: icon)
                .font(.system(size: 14, weight: .semibold))
                .foregroundColor(AppColors.primary)
                .frame(width: 20)

            VStack(alignment: .leading, spacing: 2) {
                Text(label)
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)

                Text(value)
                    .font(.appBodyBold)
                    .foregroundColor(AppColors.primaryText)
                    .lineLimit(1)
            }

            Spacer()
        }
        .padding(AppSpacing.sm)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .fill(AppColors.surfaceElevated.opacity(0.5))
        )
    }
}

// MARK: - Condition Tag

private enum ConditionSeverity {
    case low, warning, critical

    var color: Color {
        switch self {
        case .low: return Color.yellow
        case .warning: return Color.orange
        case .critical: return Color.red
        }
    }
}

private struct ConditionTag: View {
    let name: String
    let severity: ConditionSeverity

    var body: some View {
        HStack(spacing: AppSpacing.xs) {
            Circle()
                .fill(severity.color)
                .frame(width: 8, height: 8)

            Text(name)
                .font(.appCaption)
                .foregroundColor(AppColors.primaryText)

            Spacer()
        }
        .padding(AppSpacing.sm)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .fill(severity.color.opacity(0.1))
        )
        .overlay(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .strokeBorder(severity.color.opacity(0.3), lineWidth: 1)
        )
    }
}

// MARK: - Habit Row

private struct ProfileHabitRow: View {
    let habit: Habit

    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                Text(habit.name)
                    .font(.appBody)
                    .foregroundColor(AppColors.primaryText)

                Text(habit.status.capitalized)
                    .font(.appCaption)
                    .foregroundColor(statusColor)
            }

            Spacer()

            if habit.status == "quitting" {
                VStack(alignment: .trailing, spacing: AppSpacing.xs) {
                    Text("\(habit.quitProgress)/30 days")
                        .font(.appCaptionBold)
                        .foregroundColor(AppColors.secondaryText)

                    ProgressView(value: Double(habit.quitProgress), total: 30)
                        .progressViewStyle(LinearProgressViewStyle(tint: Color.green))
                        .frame(width: 60)
                }
            }
        }
        .padding(AppSpacing.sm)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .fill(AppColors.surfaceElevated.opacity(0.5))
        )
    }

    private var statusColor: Color {
        switch habit.status {
        case "active": return Color.orange
        case "quitting": return Color.green
        default: return AppColors.secondaryText
        }
    }
}

// MARK: - Preview

#if DEBUG
struct StatsHealthSection_Previews: PreviewProvider {
    static var previews: some View {
        let samplePerson = Person()
        samplePerson.id = "123"
        samplePerson.firstname = "Emma"
        samplePerson.health = 45
        samplePerson.happiness = 78
        samplePerson.intelligence = 85
        samplePerson.prestige = 60
        samplePerson.calcEnergy = 65
        samplePerson.mood = "Happy"
        samplePerson.sex = "Female"
        samplePerson.ageYears = 28
        // Note: Habits would normally come from the backend
        // Preview shows without habits since Habit requires Decoder init

        return ScrollView {
            StatsHealthSection(person: samplePerson)
                .padding()
        }
        .background(AppColors.background)
    }
}
#endif
