import SwiftUI

public struct AddUserRow<AvatarView: View>: View {
    let displayName: String
    let subtitle: String?
    let avatarView: AvatarView
    let buttonTitle: String
    let isLoading: Bool
    let action: () -> Void

    public init(
        displayName: String,
        subtitle: String?,
        avatarView: AvatarView,
        buttonTitle: String,
        isLoading: Bool,
        action: @escaping () -> Void
    ) {
        self.displayName = displayName
        self.subtitle = subtitle
        self.avatarView = avatarView
        self.buttonTitle = buttonTitle
        self.isLoading = isLoading
        self.action = action
    }

    public var body: some View {
        HStack(spacing: 8) {
            avatarView
                .frame(width: 40, height: 40)
                .mask(Circle())

            VStack(alignment: .leading, spacing: 1) {
                Text(displayName)
                    .typographyV1(.caption.neueMontrealMedium())
                    .foregroundStyle(Color.SemanticV1.textPrimary)
                    .lineLimit(1)

                if let subtitle, !subtitle.isEmpty {
                    Text(subtitle)
                        .typographyV1(.caption5.neueMontrealRegular())
                        .foregroundStyle(Color.SemanticV1.textBrand)
                        .lineLimit(1)
                }
            }

            Spacer()

            Button {
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
                action()
            } label: {
                Text(buttonTitle)
                    .typographyV1(.body1.neueMontrealMedium())
                    .foregroundStyle(Color.SemanticV1.textInvert)
                    .padding(.horizontal, 16)
                    .padding(.vertical, 8)
                    .opacity(isLoading ? 0 : 1)
                    .overlay {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle(tint: Color.SemanticV1.textInvert))
                            .opacity(isLoading ? 1 : 0)
                            .id(UUID()) // `ProgressView()` needs this to work properly in Lists
                    }
                    .background(RoundedRectangle(cornerRadius: 8).fill(Color.SemanticV1.backgroundInvert))
            }
            .buttonStyle(.borderless)
        }
        .padding(.vertical, 16)
    }
}
