//
//  RelationshipSection.swift
//  lichunWebsocket
//
//  Relationship section with connection stats, family tree, shared history
//

import SwiftUI

struct RelationshipSection: View {
    @ObservedObject var person: Person
    let onViewChat: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.lg) {
            // Connection stats card
            connectionCard

            // Relationship types
            if !person.relationships.isEmpty {
                relationshipTypesSection
            }

            // Family connections (if any)
            if hasFamily {
                familySection
            }

            // View conversation history button
            chatHistoryButton
        }
    }

    // MARK: - Connection Card

    private var connectionCard: some View {
        BaseCard(showShadow: false) {
            VStack(spacing: AppSpacing.md) {
                // Affinity
                VStack(alignment: .leading, spacing: AppSpacing.xs) {
                    HStack {
                        Image(systemName: "heart.fill")
                            .font(.system(size: 14))
                            .foregroundColor(AppColors.primary)

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

                        Spacer()

                        Text(affinityDescription)
                            .font(.appCaption)
                            .foregroundColor(affinityColor)
                    }

                    CozyStatBar(
                        label: nil,
                        value: person.affinity,
                        color: affinityColor,
                        showPercentage: false,
                        height: 8
                    )
                }

                Divider()
                    .background(AppColors.secondaryText.opacity(0.2))

                // Relationship status row
                HStack {
                    StatItem(
                        icon: "clock.fill",
                        label: "Known for",
                        value: knownForDuration
                    )

                    Spacer()

                    StatItem(
                        icon: "bubble.left.and.bubble.right.fill",
                        label: "Conversations",
                        value: "\(person.availableConversations.count)"
                    )
                }
            }
        }
    }

    private var affinityDescription: String {
        switch person.affinity {
        case 90...100: return "Best Friends"
        case 75..<90: return "Close"
        case 50..<75: return "Friendly"
        case 25..<50: return "Acquaintance"
        case 0..<25: return "Distant"
        default: return "Unknown"
        }
    }

    private var affinityColor: Color {
        switch person.affinity {
        case 75...100: return Color.green
        case 50..<75: return AppColors.primary
        case 25..<50: return Color.orange
        default: return Color.red
        }
    }

    private var knownForDuration: String {
        // This would ideally come from the backend
        // For now, return a placeholder based on affinity
        if person.affinity >= 75 {
            return "Years"
        } else if person.affinity >= 50 {
            return "Months"
        } else if person.affinity >= 25 {
            return "Weeks"
        } else {
            return "Days"
        }
    }

    // MARK: - Relationship Types Section

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

                Text("Connection Types")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            FlowLayout(spacing: AppSpacing.xs) {
                ForEach(person.relationships, id: \.self) { relationship in
                    RelationshipTag(type: relationship)
                }
            }
        }
    }

    // MARK: - Family Section

    private var hasFamily: Bool {
        let familyTypes = ["parent", "child", "sibling", "spouse", "grandparent", "grandchild", "aunt", "uncle", "cousin"]
        return person.relationships.contains { rel in
            familyTypes.contains(rel.lowercased())
        }
    }

    private var familySection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.xs) {
                Image(systemName: "figure.2.and.child.holdinghands")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(AppColors.primary)

                Text("Family Connection")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            Text("This person is part of your family tree.")
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
                .padding(AppSpacing.sm)
                .frame(maxWidth: .infinity, alignment: .leading)
                .background(
                    RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                        .fill(AppColors.primary.opacity(0.1))
                )
        }
    }

    // MARK: - Chat History Button

    private var chatHistoryButton: some View {
        Button(action: {
            hapticFeedback(style: .light)
            onViewChat()
        }) {
            HStack {
                Image(systemName: "message.fill")
                    .font(.system(size: 16, weight: .semibold))

                Text("View Conversation History")
                    .font(.appBodyBold)

                Spacer()

                Image(systemName: "chevron.right")
                    .font(.system(size: 14, weight: .semibold))
            }
            .foregroundColor(AppColors.primary)
            .padding(AppSpacing.md)
            .background(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .fill(AppColors.primary.opacity(0.1))
            )
            .overlay(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                    .strokeBorder(AppColors.primary.opacity(0.3), lineWidth: 1)
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// MARK: - Stat Item Component

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

    var body: some View {
        VStack(alignment: .center, spacing: AppSpacing.xs) {
            Image(systemName: icon)
                .font(.system(size: 16, weight: .semibold))
                .foregroundColor(AppColors.primary)

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

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

// MARK: - Relationship Tag Component

private struct RelationshipTag: View {
    let type: String

    var body: some View {
        HStack(spacing: AppSpacing.xs) {
            Image(systemName: iconForType)
                .font(.system(size: 12))
                .foregroundColor(colorForType)

            Text(type.capitalized)
                .font(.appCaption)
                .foregroundColor(AppColors.primaryText)
        }
        .padding(.horizontal, AppSpacing.sm)
        .padding(.vertical, AppSpacing.xs)
        .background(
            Capsule()
                .fill(colorForType.opacity(0.15))
        )
    }

    private var iconForType: String {
        switch type.lowercased() {
        case "parent": return "figure.stand"
        case "child": return "figure.and.child.holdinghands"
        case "sibling": return "person.2.fill"
        case "spouse", "partner": return "heart.fill"
        case "friend": return "person.fill.checkmark"
        case "classmate": return "graduationcap.fill"
        case "coworker": return "briefcase.fill"
        case "crush": return "heart.circle.fill"
        default: return "person.fill"
        }
    }

    private var colorForType: Color {
        switch type.lowercased() {
        case "parent", "child", "sibling": return AppColors.primary
        case "spouse", "partner", "crush": return Color.pink
        case "friend": return Color.green
        case "classmate": return Color.blue
        case "coworker": return Color.orange
        default: return AppColors.accent
        }
    }
}

// MARK: - Preview

#if DEBUG
struct RelationshipSection_Previews: PreviewProvider {
    static var previews: some View {
        let samplePerson = Person()
        samplePerson.id = "123"
        samplePerson.firstname = "Emma"
        samplePerson.affinity = 75
        samplePerson.relationships = ["friend", "classmate", "crush"]

        return ScrollView {
            RelationshipSection(person: samplePerson) {
                print("View chat tapped")
            }
            .padding()
        }
        .background(AppColors.background)
    }
}
#endif
