import SwiftUI
import Bedrock
import SwiftData

struct BusinessCardView: View {
    let card: BusinessCard
    var isCompact: Bool = false

    var body: some View {
        VStack(spacing: 0) {
            // Banner with logo
            CardBannerView(card: card)
            
            // Content area with avatar overlapping
            CardContentView(card: card, isCompact: isCompact)
                .offset(y: -Design.CardSize.avatarOverlap)
                .padding(.bottom, -Design.CardSize.avatarOverlap)
        }
        .background(Color.AppBackground.elevated)
        .clipShape(.rect(cornerRadius: Design.CornerRadius.xLarge))
        .shadow(
            color: Color.Text.secondary.opacity(Design.Opacity.hint),
            radius: Design.Shadow.radiusLarge,
            x: Design.Shadow.offsetNone,
            y: Design.Shadow.offsetMedium
        )
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(String.localized("Business card"))
        .accessibilityValue("\(card.effectiveDisplayName), \(card.role), \(card.company)")
    }
}

// MARK: - Banner View

private struct CardBannerView: View {
    let card: BusinessCard
    
    var body: some View {
        ZStack {
            // Background: cover photo or gradient
            if let coverPhotoData = card.coverPhotoData, let uiImage = UIImage(data: coverPhotoData) {
                Image(uiImage: uiImage)
                    .resizable()
                    .scaledToFill()
                    .frame(height: Design.CardSize.bannerHeight)
                    .clipped()
            } else {
                // Fallback gradient
                LinearGradient(
                    colors: [card.theme.primaryColor, card.theme.secondaryColor],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            }
            
            // Company logo overlay
            if let logoData = card.logoData, let uiImage = UIImage(data: logoData) {
                Image(uiImage: uiImage)
                    .resizable()
                    .scaledToFit()
                    .frame(height: Design.CardSize.logoSize)
            } else if card.coverPhotoData == nil && !card.company.isEmpty {
                // Only show company initial if no cover photo and no logo
                Text(card.company.prefix(1).uppercased())
                    .font(.system(size: Design.BaseFontSize.display, weight: .bold, design: .rounded))
                    .foregroundStyle(card.theme.textColor.opacity(Design.Opacity.medium))
            }
        }
        .frame(height: Design.CardSize.bannerHeight)
    }
}

// MARK: - Content View

private struct CardContentView: View {
    let card: BusinessCard
    let isCompact: Bool
    
    private var textColor: Color { Color.Text.primary }
    
    var body: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.medium) {
            // Avatar and label row
            HStack(alignment: .bottom) {
                ProfileAvatarView(card: card)
                Spacer()
                LabelBadgeView(label: card.label, accentColor: card.theme.accentColor, textColor: card.theme.textColor)
                    .padding(.bottom, Design.CardSize.avatarOverlap)
            }
            
            // Name and title
            VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                HStack(spacing: Design.Spacing.xSmall) {
                    Text(card.effectiveDisplayName)
                        .font(.title2)
                        .bold()
                        .foregroundStyle(textColor)
                    
                    if !card.pronouns.isEmpty {
                        Text("(\(card.pronouns))")
                            .font(.subheadline)
                            .foregroundStyle(Color.Text.secondary)
                    }
                }
                
                Text(card.role)
                    .font(.headline)
                    .foregroundStyle(textColor)
                
                Text(card.company)
                    .font(.subheadline)
                    .foregroundStyle(Color.Text.secondary)
                
                if !card.headline.isEmpty {
                    Text(card.headline)
                        .font(.caption)
                        .foregroundStyle(Color.Text.secondary)
                        .padding(.top, Design.Spacing.xxSmall)
                }
            }
            
            if !isCompact {
                Divider()
                    .padding(.vertical, Design.Spacing.xSmall)
                
                // Contact fields from array (preferred) or legacy properties
                ContactFieldsListView(card: card)
            }
        }
        .padding(.horizontal, Design.Spacing.large)
        .padding(.bottom, Design.Spacing.large)
    }
}

// MARK: - Profile Avatar

private struct ProfileAvatarView: View {
    let card: BusinessCard
    
    var body: some View {
        Group {
            if let photoData = card.photoData, let uiImage = UIImage(data: photoData) {
                Image(uiImage: uiImage)
                    .resizable()
                    .scaledToFill()
            } else {
                Image(systemName: card.avatarSystemName)
                    .font(.system(size: Design.BaseFontSize.title))
                    .foregroundStyle(card.theme.textColor)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(card.theme.accentColor)
            }
        }
        .frame(width: Design.CardSize.avatarLarge, height: Design.CardSize.avatarLarge)
        .clipShape(.circle)
        .overlay(
            Circle()
                .stroke(Color.AppBackground.elevated, lineWidth: Design.LineWidth.thick)
        )
        .shadow(
            color: Color.Text.secondary.opacity(Design.Opacity.hint),
            radius: Design.Shadow.radiusSmall,
            x: Design.Shadow.offsetNone,
            y: Design.Shadow.offsetSmall
        )
    }
}

// MARK: - Contact Fields List

private struct ContactFieldsListView: View {
    @Environment(\.openURL) private var openURL
    let card: BusinessCard
    
    var body: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            // New contact fields array (preferred)
            ForEach(card.orderedContactFields) { field in
                ContactFieldRowView(field: field) {
                    if let url = field.buildURL() {
                        openURL(url)
                    }
                }
            }
            
        }
    }
}

/// A clickable row for a contact field
private struct ContactFieldRowView: View {
    let field: ContactField
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            HStack(alignment: .top, spacing: Design.Spacing.medium) {
                // Icon with brand color
                field.iconImage()
                    .font(.body)
                    .foregroundStyle(.white)
                    .frame(width: Design.CardSize.socialIconSize, height: Design.CardSize.socialIconSize)
                    .background(field.iconColor)
                    .clipShape(.circle)
                
                VStack(alignment: .leading, spacing: 0) {
                    // Value (uses displayValue for formatted output, e.g., multi-line addresses)
                    Text(field.displayValue)
                        .font(.subheadline)
                        .foregroundStyle(Color.Text.primary)
                        .multilineTextAlignment(.leading)
                    
                    // Title/Label
                    Text(field.title.isEmpty ? field.displayName : field.title)
                        .font(.caption)
                        .foregroundStyle(Color.Text.secondary)
                        .lineLimit(1)
                }
                
                Spacer()
                
                // Action indicator
                Image(systemName: "chevron.right")
                    .font(.caption)
                    .foregroundStyle(Color.Text.tertiary)
            }
            .contentShape(.rect)
        }
        .buttonStyle(.plain)
        .accessibilityLabel("\(field.displayName): \(field.value)")
        .accessibilityHint(field.title.isEmpty ? String(localized: "Opens \(field.displayName)") : field.title)
    }
}

// MARK: - Preview

#Preview {
    @Previewable @State var card: BusinessCard = {
        let card = BusinessCard(
            displayName: "Matt Bruce",
            role: "Lead iOS Developer",
            company: "Toyota",
            themeName: "Coral",
            layoutStyleRawValue: "stacked",
            headline: "Building the future of mobility"
        )
        
        // Add contact fields manually without SwiftData
        let emailField = ContactField(typeId: "email", value: "matt.bruce@toyota.com", title: "Work", orderIndex: 0)
        let phoneField = ContactField(typeId: "phone", value: "+1 (214) 755-1043", title: "Cell", orderIndex: 1)
        let websiteField = ContactField(typeId: "website", value: "toyota.com", title: "", orderIndex: 2)
        
        // Create structured address
        let address = PostalAddress(
            street: "6565 Headquarters Dr",
            city: "Plano",
            state: "TX",
            postalCode: "75024"
        )
        let addressField = ContactField(typeId: "address", value: address.toJSON(), title: "Work", orderIndex: 3)
        
        let linkedInField = ContactField(typeId: "linkedIn", value: "linkedin.com/in/mattbruce", title: "", orderIndex: 4)
        let twitterField = ContactField(typeId: "twitter", value: "twitter.com/mattbruce", title: "", orderIndex: 5)
        
        card.contactFields = [emailField, phoneField, websiteField, addressField, linkedInField, twitterField]
        
        return card
    }()
    
    BusinessCardView(card: card)
        .padding()
        .background(Color.AppBackground.base)
}
