//
//  WeChatShareSheet.swift
//  suixinkan
//

import SwiftUI
import UIKit

/// 微信分享选项面板，支持好友/朋友圈及系统分享兜底。
struct WeChatShareSheet: View {
    let title: String
    let description: String
    let url: String
    let thumbImage: UIImage?
    let onResult: (String) -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var isPresentingSystemShare = false

    var body: some View {
        NavigationStack {
            List {
                if WeChatShareService.isWeChatAvailable {
                    shareButton("微信好友", systemImage: "message.fill") {
                        share(scene: .session)
                    }
                    shareButton("朋友圈", systemImage: "person.2.fill") {
                        share(scene: .timeline)
                    }
                }
                shareButton("更多分享", systemImage: "square.and.arrow.up") {
                    isPresentingSystemShare = true
                }
            }
            .navigationTitle("分享")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") { dismiss() }
                }
            }
        }
        .sheet(isPresented: $isPresentingSystemShare) {
            let text = shareText
            ActivityShareView(activityItems: [text]) {
                onResult("已打开系统分享")
                dismiss()
            }
        }
    }

    private var shareText: String {
        let trimmedURL = url.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedURL.isEmpty else { return title }
        return "\(title)\n\(trimmedURL)"
    }

    private func shareButton(_ label: String, systemImage: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Label(label, systemImage: systemImage)
        }
    }

    private func share(scene: WeChatShareScene) {
        let payload = WeChatWebPageSharePayload(
            title: title,
            description: description,
            url: url
        )
        let thumb = thumbImage ?? WeChatShareService.defaultThumbImage()
        WeChatShareService.shareWebPage(payload, scene: scene, thumbImage: thumb) { result in
            switch result {
            case .success:
                onResult("已分享到\(scene.title)")
            case .cancelled:
                onResult("已取消分享")
            case .notInstalled:
                isPresentingSystemShare = true
            case .unsupported:
                onResult("当前微信版本不支持分享")
            case .invalidPayload(let message):
                onResult(message)
            case .sendFailed, .unknown:
                onResult("分享失败，请稍后重试")
            }
            dismiss()
        }
    }
}

/// 系统分享面板封装。
private struct ActivityShareView: UIViewControllerRepresentable {
    let activityItems: [Any]
    let onComplete: () -> Void

    func makeUIViewController(context: Context) -> UIActivityViewController {
        let controller = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        controller.completionWithItemsHandler = { _, _, _, _ in
            onComplete()
        }
        return controller
    }

    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}
