import APIClient
import ComponentLibrary
import Dependencies
import Foundation
import Localization
import ShareAssetClient
import SwiftUI
import Utilities

extension Clip: Shareable {
    public static let sheetTitle = L10n.FeatureShare.shareSongTitle

    public var shareActions: Set<ShareableTarget> {
        ShareableTarget.allCases
    }

    public var supportsVideoRendering: Bool {
        true
    }

    public var preview: some View {
        VStack(spacing: 20) {
            RemoteImage(url: largeImageUrl, fallbackId: id.remoteId)
                .aspectRatio(0.56, contentMode: .fit)
                .clipShape(.rect(cornerRadius: 20))
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(Color.SemanticV1.borderPrimary, lineWidth: 0.5)
                )

            VStack(spacing: 4) {
                Text(title)
                    .typographyV1(.headline5)
                    .lineLimit(2)
                    .multilineTextAlignment(.center)
                    .foregroundStyle(Color.SemanticV1.textPrimary)

                HStack(spacing: 5) {
                    RemoteImage(url: avatarImageUrl, fallbackId: userId)
                        .frame(width: 20, height: 20)
                        .clipShape(.circle)

                    Text(handle)
                        .typographyV1(.caption3)
                        .foregroundStyle(Color.SemanticV1.textPrimary.opacity(0.8))
                }
            }
        }
    }

    public var shareURL: URL {
        fallbackShareURL
    }

    public var shareText: String? {
        L10n.FeatureShare.shareSongSubject
    }

    /// Overrides `shareURL` when not `nil`
    public func getTemporaryAttributedShareURL(source _: HooksFeedSource?) async throws -> ShareAttribution? {
        @Dependency(\.apiClientV2) var api

        return try await api.postShareLink(
            contentId: id.remoteId,
            contentType: "song",
            platform: "temp",
            source: "ios",
            recommendationMetadata: nil
        )
    }

    public func register(shareAttribution: ShareAttribution, for platform: ShareableTarget.Platform?) async throws {
        @Dependency(\.apiClientV2) var api

        return try await api.patchShareLink(
            UpdateShareLinkRequest(
                platform: platform?.rawValue.lowercased(),
                shareId: shareAttribution.shareId
            )
        )
    }
}
