//
//  LifeStorySection.swift
//  lichunWebsocket
//
//  Life story section with education, career, and daily schedule
//

import SwiftUI

struct LifeStorySection: View {
    @ObservedObject var person: Person
    let currentHour: Int

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.lg) {
            // Current status card
            currentStatusCard

            // Education history
            if hasEducation {
                educationSection
            }

            // Career info
            if !person.occupation.isEmpty {
                careerSection
            }

            // Daily schedule
            if !person.activities.isEmpty {
                scheduleSection
            }
        }
    }

    // MARK: - Current Status Card

    private var currentStatusCard: some View {
        BaseCard(showShadow: false) {
            VStack(alignment: .leading, spacing: AppSpacing.md) {
                HStack(spacing: AppSpacing.xs) {
                    Image(systemName: "info.circle.fill")
                        .font(.system(size: 14, weight: .semibold))
                        .foregroundColor(AppColors.primary)

                    Text("Current Status")
                        .font(.appCaptionBold)
                        .foregroundColor(AppColors.secondaryText)
                }

                VStack(spacing: AppSpacing.sm) {
                    StatusRow(
                        icon: "graduationcap.fill",
                        label: "Education",
                        value: person.education.isEmpty ? "None" : person.education
                    )

                    StatusRow(
                        icon: "briefcase.fill",
                        label: "Occupation",
                        value: person.occupation.isEmpty ? "Unemployed" : person.occupation
                    )

                    StatusRow(
                        icon: "location.fill",
                        label: "Location",
                        value: person.location.isEmpty ? "Unknown" : person.location.capitalized
                    )

                    if !person.intraDayMessage.isEmpty {
                        StatusRow(
                            icon: "figure.walk",
                            label: "Activity",
                            value: person.intraDayMessage
                        )
                    }
                }
            }
        }
    }

    // MARK: - Education Section

    private var hasEducation: Bool {
        person.currentEducation != nil || !person.education.isEmpty
    }

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

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

            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                if let currentEd = person.currentEducation {
                    EducationCard(
                        title: currentEd.location,
                        subtitle: currentEd.educationLevel,
                        gpa: currentEd.GPA,
                        isCurrent: true
                    )
                } else if !person.education.isEmpty {
                    EducationCard(
                        title: person.education,
                        subtitle: educationLevel,
                        gpa: nil,
                        isCurrent: true
                    )
                }
            }
        }
    }

    private var educationLevel: String {
        switch person.ageYears {
        case 5..<12: return "Elementary School"
        case 12..<18: return "High School"
        case 18..<22: return "College"
        default: return "Graduate"
        }
    }

    // MARK: - Career Section

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

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

            HStack {
                VStack(alignment: .leading, spacing: AppSpacing.xs) {
                    Text(person.occupation)
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primaryText)

                    if person.ownsBusiness {
                        Text("Business Owner")
                            .font(.appCaption)
                            .foregroundColor(AppColors.accent)
                    }
                }

                Spacer()

                if person.money > 0 {
                    VStack(alignment: .trailing, spacing: AppSpacing.xs) {
                        Text("Income")
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)

                        Text("$\(formatMoney(person.money))")
                            .font(.appBodyBold)
                            .foregroundColor(Color.green)
                    }
                }
            }
            .padding(AppSpacing.md)
            .background(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .fill(AppColors.surfaceElevated.opacity(0.5))
            )
        }
    }

    private func formatMoney(_ amount: Int) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.string(from: NSNumber(value: amount)) ?? "\(amount)"
    }

    // MARK: - Schedule Section

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

                Text("Daily Schedule")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            VStack(spacing: AppSpacing.xs) {
                ForEach(Array(person.activities.enumerated()), id: \.offset) { index, activity in
                    ScheduleItem(
                        title: activity.title,
                        time: "Active",
                        isCurrent: isCurrentActivity(activity)
                    )
                }
            }
        }
    }

    private func isCurrentActivity(_ activity: any ActivityProtocol) -> Bool {
        // Check if this activity is happening at the current hour
        // This is a simplified check - real implementation would be more complex
        return person.intraDayMessage.lowercased().contains(activity.title.lowercased())
    }
}

// MARK: - Status Row Component

private struct StatusRow: 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)

            Text(label)
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
                .frame(width: 80, alignment: .leading)

            Spacer()

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

// MARK: - Education Card Component

private struct EducationCard: View {
    let title: String
    let subtitle: String
    let gpa: Double?
    let isCurrent: Bool

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

                    if isCurrent {
                        Text("Current")
                            .font(.system(size: 10, weight: .bold))
                            .foregroundColor(.white)
                            .padding(.horizontal, 6)
                            .padding(.vertical, 2)
                            .background(Color.green)
                            .cornerRadius(4)
                    }
                }

                Text(subtitle)
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }

            Spacer()

            if let gpa = gpa {
                VStack(alignment: .trailing, spacing: AppSpacing.xs) {
                    Text("GPA")
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)

                    Text(String(format: "%.2f", gpa))
                        .font(.appBodyBold)
                        .foregroundColor(gpaColor(gpa))
                }
            }
        }
        .padding(AppSpacing.md)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .fill(AppColors.surfaceElevated.opacity(0.5))
        )
    }

    private func gpaColor(_ gpa: Double) -> Color {
        if gpa >= 3.5 {
            return Color.green
        } else if gpa >= 2.5 {
            return Color.yellow
        } else {
            return Color.orange
        }
    }
}

// MARK: - Schedule Item Component

private struct ScheduleItem: View {
    let title: String
    let time: String
    let isCurrent: Bool

    var body: some View {
        HStack {
            Circle()
                .fill(isCurrent ? AppColors.primary : AppColors.secondaryText.opacity(0.3))
                .frame(width: 8, height: 8)

            Text(time)
                .font(.appCaption)
                .foregroundColor(isCurrent ? AppColors.primary : AppColors.secondaryText)
                .frame(width: 60, alignment: .leading)

            Text(title)
                .font(isCurrent ? .appBodyBold : .appBody)
                .foregroundColor(isCurrent ? AppColors.primaryText : AppColors.secondaryText)

            Spacer()

            if isCurrent {
                Text("Now")
                    .font(.system(size: 10, weight: .bold))
                    .foregroundColor(.white)
                    .padding(.horizontal, 6)
                    .padding(.vertical, 2)
                    .background(AppColors.primary)
                    .cornerRadius(4)
            }
        }
        .padding(.vertical, AppSpacing.xs)
    }
}

// MARK: - Preview

#if DEBUG
struct LifeStorySection_Previews: PreviewProvider {
    static var previews: some View {
        let samplePerson = Person()
        samplePerson.id = "123"
        samplePerson.firstname = "Emma"
        samplePerson.education = "Stanford University"
        samplePerson.occupation = "Software Engineer"
        samplePerson.location = "Office"
        samplePerson.intraDayMessage = "Working on a project"
        samplePerson.money = 75000

        return ScrollView {
            LifeStorySection(person: samplePerson, currentHour: 14)
                .padding()
        }
        .background(AppColors.background)
    }
}
#endif
