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

extension Hook: Shareable {
    public static let sheetTitle = L10n.FeatureShare.shareHookTitle

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

    public var supportsVideoRendering: Bool {
        FeatureFlag.hooks.allowAllHookDownloads || FeatureFlag.hooks.allowSelfHookDownload
    }

    public var preview: some View {
        VStack(spacing: 14) {
            RemoteImage(url: thumbnailImageUrl, fallbackId: id)
                .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: user?.avatarImageUrl, fallbackId: user?.id)
                        .frame(width: 20, height: 20)
                        .clipShape(.circle)

                    Text(user?.handle ?? "@unknown")
                        .typographyV1(.caption3)
                        .foregroundStyle(Color.SemanticV1.textPrimary.opacity(0.8))
                }
            }
        }
    }

    public var shareURL: URL {
        fallbackShareURL
    }

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

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

        do {
            _ = try await api.incrementShareCount(hookId: id, recommendationMetadata: .init(
                contextType: (source ?? .unknown).analyticsContext.contextType,
                hookId: id,
                recommendationItemId: recommendationItemId
            ))
        } catch {
            // Log error but don't fail the share flow
            log.telemetry.error(error, message: "Failed to increment share count.")
        }

        return try await api.postShareLink(
            contentId: id,
            contentType: "hook",
            platform: "temp",
            source: "ios",
            recommendationMetadata: .init(
                contextType: (source ?? .unknown).analyticsContext.contextType,
                hookId: id,
                recommendationItemId: recommendationItemId
            )
        )
    }

    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
            )
        )
    }
}
