import APIClient
import ComposableArchitecture
import Localization
import SwiftUI

public struct ProfileShareCardView: View {
    public enum Account {
        case profile(Profile)
        case user(User)

        func isMe(me: Me) -> Bool {
            switch self {
            case .profile(let profile): profile.id == me.user.id
            case .user(let user): user.id == me.user.id
            }
        }

        var shareType: Share.State.ShareType {
            switch self {
            case .profile(let profile): .profile(profile)
            case .user(let user): .me(user)
            }
        }

        var name: String {
            switch self {
            case .profile(let profile): profile.displayName ?? profile.handle
            case .user(let user): user.displayName ?? user.handle
            }
        }

        var caption: String? {
            switch self {
            case .profile(let profile): L10n.FeatureShare.shareSongs(profile.stats.songs)
            case .user: nil
            }
        }

        var avatarImageUrl: String? {
            switch self {
            case .profile(let profile): profile.avatarImageUrl
            case .user(let user): user.avatarImageUrl
            }
        }

        var id: String {
            switch self {
            case .profile(let profile): profile.id
            case .user(let user): user.id
            }
        }

        func cta(me: Me) -> String {
            switch self {
            case .profile: isMe(me: me) ? L10n.FeatureShare.viewMySongsOnSuno : L10n.FeatureShare.listenOnSuno
            case .user: L10n.FeatureShare.acceptInvite
            }
        }

        var authorInfo: AuthorInfo {
            switch self {
            case .profile(let profile):
                AuthorInfo(
                    authorId: profile.id,
                    displayName: name,
                    imageUrl: profile.avatarImageUrl
                )

            case .user(let user):
                AuthorInfo(
                    authorId: user.id,
                    displayName: name,
                    imageUrl: user.avatarImageUrl
                )
            }
        }
    }

    let account: Account
    @Shared var me: Me

    public init(_ account: Account, me: Shared<Me>) {
        self.account = account
        self._me = me
    }

    public var body: some View {
        ShareCardView(
            account.shareType,
            title: account.name,
            tags: nil,
            cta: account.cta(me: me),
            caption: account.caption,
            authorInfo: account.authorInfo,
            imageUrl: account.avatarImageUrl,
            fallbackId: account.id
        )
    }
}
