import APIClient
import ComponentLibrary
import ComposableArchitecture
import Localization
import SwiftUI

public struct FollowListItemView: View {
    var user: MiniProfile
    var totalUsers: Int
    var formattedCreateAt: String
    var followTapped: (MiniProfile) -> Void
    var followInProgress: Bool
    var userTapped: (MiniProfile) -> Void

    var usersText: String {
        let displayName = user.displayName.trimmingCharacters(in: .whitespaces)
        if totalUsers == 1 {
            // Steve
            return displayName
        } else {
            // Steve and 3 more
            return L10n.FeatureProfile.userAndNMore(displayName, totalUsers - 1)
        }
    }

    public var body: some View {
        followView
            .listRowInsets(.init())
            .listRowBackground(Color.clear)
            .alignmentGuide(.listRowSeparatorLeading) { d in
                d[.leading] + 24
            }
    }

    private var followView: some View {
        HStack(spacing: 16) {
            avatar

            VStack(alignment: .leading, spacing: 2) {
                Text(.init("[\(usersText)](suno://user-tapped) \(L10n.FeatureProfile.followedYou)"))
                    .typographyV1(.body1)
                    .accentColor(.SemanticV1.textPrimary)
                    .foregroundColor(.SemanticV1.textTertiary)
                    .fixedSize(horizontal: false, vertical: true)
                    .lineLimit(2)
                    .environment(\.openURL, OpenURLAction { _ in
                        userTapped(user)
                        return .handled
                    })

                Text(formattedCreateAt)
                    .typographyV1(.caption4)
                    .foregroundColor(.SemanticV1.textSecondary)
                    .lineLimit(1)
            }
            .multilineTextAlignment(.leading)
            .frame(maxWidth: .infinity, alignment: .leading)

            followButton
        }
        .contentShape(.rect)
        .padding(.vertical, 16)
    }

    @ViewBuilder
    private var avatar: some View {
        RemoteImage(url: user.avatarImageUrl, fallbackId: user.handle)
            .clipShape(.rect(cornerRadius: 20))
            .frame(width: 40, height: 40)
            .onTapGesture { userTapped(user) }
    }

    @ViewBuilder
    private var followButton: some View {
        PrimaryButtonV1(
            title: user.isFollowing ? L10n.FeatureProfile.following : L10n.FeatureProfile.follow,
            isLoading: followInProgress,
            colorCombination: .dark,
            preferredSize: .smallAdaptive,
            action: { followTapped(user) }
        )
        .background(Color.SemanticV1.backgroundPrimary)
    }
}
