//
//  ItemsSection.swift
//  lichunWebsocket
//
//  Items & Possessions section with financials and inventory
//

import SwiftUI

struct ItemsSection: View {
    @ObservedObject var person: Person

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.lg) {
            // Financial summary
            financialSection

            // Inventory
            if !person.items.isEmpty {
                inventorySection
            } else {
                emptyInventorySection
            }
        }
    }

    // MARK: - Financial Section

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

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

            HStack(spacing: AppSpacing.md) {
                FinanceCard(
                    icon: "banknote",
                    label: "Money",
                    value: "$\(formatNumber(person.money))",
                    color: Color.green
                )

                FinanceCard(
                    icon: "diamond.fill",
                    label: "Diamonds",
                    value: "\(person.diamonds)",
                    color: Color.cyan
                )
            }
        }
    }

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

    // MARK: - Inventory Section

    private var inventorySection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "bag.fill")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(AppColors.accent)

                Text("Inventory")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)

                Spacer()

                Text("\(person.items.count) items")
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }

            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: AppSpacing.sm) {
                    ForEach(person.items, id: \.id) { item in
                        ItemCard(item: item)
                    }
                }
                .padding(.horizontal, AppSpacing.xs)
            }
        }
    }

    // MARK: - Empty Inventory

    private var emptyInventorySection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "bag.fill")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(AppColors.accent)

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

            HStack {
                Spacer()

                VStack(spacing: AppSpacing.sm) {
                    Image(systemName: "archivebox")
                        .font(.system(size: 32))
                        .foregroundColor(AppColors.secondaryText.opacity(0.5))

                    Text("No items")
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                }

                Spacer()
            }
            .padding(.vertical, AppSpacing.lg)
            .background(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .fill(AppColors.surfaceElevated.opacity(0.3))
            )
        }
    }
}

// MARK: - Finance Card Component

private struct FinanceCard: View {
    let icon: String
    let label: String
    let value: String
    let color: Color

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: icon)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(color)

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

            Text(value)
                .font(.system(size: 20, weight: .bold, design: .rounded))
                .foregroundColor(AppColors.primaryText)
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(AppSpacing.md)
        .background(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .fill(color.opacity(0.1))
        )
        .overlay(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .strokeBorder(color.opacity(0.3), lineWidth: 1)
        )
    }
}

// MARK: - Item Card Component

private struct ItemCard: View {
    let item: StoreItem

    var body: some View {
        VStack(spacing: AppSpacing.xs) {
            ZStack {
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .fill(itemColor.opacity(0.15))
                    .frame(width: 60, height: 60)

                if let imageURL = item.image, !imageURL.isEmpty {
                    AsyncImage(url: URL(string: imageURL)) { phase in
                        switch phase {
                        case .success(let image):
                            image
                                .resizable()
                                .scaledToFit()
                                .frame(width: 40, height: 40)
                                .onAppear {
                                    print("🛍️ InventoryItem: ✅ Loaded '\(item.name)' from: \(imageURL)")
                                }
                        case .failure(let error):
                            Image(systemName: "cube.fill")
                                .font(.system(size: 24, weight: .semibold))
                                .foregroundColor(itemColor)
                                .onAppear {
                                    print("🛍️ InventoryItem: ❌ Failed '\(item.name)' - URL: \(imageURL) - Error: \(error.localizedDescription)")
                                }
                        case .empty:
                            Image(systemName: "cube.fill")
                                .font(.system(size: 24, weight: .semibold))
                                .foregroundColor(itemColor)
                                .onAppear {
                                    print("🛍️ InventoryItem: 🔄 Loading '\(item.name)' from: \(imageURL)")
                                }
                        @unknown default:
                            Image(systemName: "cube.fill")
                                .font(.system(size: 24, weight: .semibold))
                                .foregroundColor(itemColor)
                        }
                    }
                } else {
                    Image(systemName: "cube.fill")
                        .font(.system(size: 24, weight: .semibold))
                        .foregroundColor(itemColor)
                        .onAppear {
                            print("🛍️ InventoryItem: ⚠️ No image URL for '\(item.name)' (id: \(item.id))")
                        }
                }
            }

            Text(item.name)
                .font(.appCaption)
                .foregroundColor(AppColors.primaryText)
                .lineLimit(1)
                .frame(width: 70)

            Text("$\(item.price)")
                .font(.system(size: 10, weight: .medium))
                .foregroundColor(AppColors.secondaryText)
        }
    }

    private var itemColor: Color {
        // Use prestige boost to determine item "rarity" color
        if item.prestigeBoost >= 50 {
            return Color.yellow  // Legendary
        } else if item.prestigeBoost >= 25 {
            return Color.purple  // Epic
        } else if item.prestigeBoost >= 10 {
            return Color.blue    // Rare
        } else {
            return AppColors.accent  // Common
        }
    }
}

// MARK: - Preview

#if DEBUG
struct ItemsSection_Previews: PreviewProvider {
    static var previews: some View {
        let samplePerson = Person()
        samplePerson.id = "123"
        samplePerson.firstname = "Emma"
        samplePerson.money = 15000
        samplePerson.diamonds = 50
        // Note: Items would normally come from the backend
        // Preview shows empty state since StoreItem requires Decoder init

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