import SwiftUI

/// Profile screen for viewing opponent (other user) information.
/// Pushed from ChatDetailView when tapping the toolbar capsule or avatar.
///
/// Desktop parity: ProfileCard (avatar + name + subtitle) →
/// Username section (copyable) → Public Key section (copyable).
struct OpponentProfileView: View {
    let route: ChatRoute

    @Environment(\.dismiss) private var dismiss
    @State private var copiedField: String?

    // MARK: - Computed properties

    private var dialog: Dialog? {
        DialogRepository.shared.dialogs[route.publicKey]
    }

    private var displayName: String {
        if let dialog, !dialog.opponentTitle.isEmpty { return dialog.opponentTitle }
        if !route.title.isEmpty { return route.title }
        if let dialog, !dialog.opponentUsername.isEmpty { return "@\(dialog.opponentUsername)" }
        if !route.username.isEmpty { return "@\(route.username)" }
        return String(route.publicKey.prefix(12))
    }

    private var username: String {
        if let dialog, !dialog.opponentUsername.isEmpty { return dialog.opponentUsername }
        return route.username
    }

    private var effectiveVerified: Int {
        if let dialog { return dialog.effectiveVerified }
        if route.verified > 0 { return route.verified }
        return 0
    }

    private var avatarInitials: String {
        RosettaColors.initials(name: displayName, publicKey: route.publicKey)
    }

    private var avatarColorIndex: Int {
        RosettaColors.avatarColorIndex(for: displayName, publicKey: route.publicKey)
    }

    private var opponentAvatar: UIImage? {
        AvatarRepository.shared.loadAvatar(publicKey: route.publicKey)
    }

    /// Desktop parity: @username • shortKey
    private var subtitleText: String {
        let shortKey = route.publicKey.prefix(4) + "..." + route.publicKey.suffix(4)
        if !username.isEmpty {
            return "@\(username) · \(shortKey)"
        }
        return String(shortKey)
    }

    // MARK: - Body

    var body: some View {
        ScrollView {
            VStack(spacing: 0) {
                profileCard
                    .padding(.top, 32)

                infoSections
                    .padding(.top, 32)
                    .padding(.horizontal, 16)
            }
        }
        .scrollIndicators(.hidden)
        .background(RosettaColors.Adaptive.background.ignoresSafeArea())
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .enableSwipeBack()
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button { dismiss() } label: { backButtonLabel }
                    .buttonStyle(.plain)
            }
        }
        .toolbarBackground(.hidden, for: .navigationBar)
    }

    // MARK: - Back Button

    private var backButtonLabel: some View {
        TelegramVectorIcon(
            pathData: TelegramIconPath.backChevron,
            viewBox: CGSize(width: 11, height: 20),
            color: .white
        )
        .frame(width: 11, height: 20)
        .allowsHitTesting(false)
        .frame(width: 36, height: 36)
        .frame(height: 44)
        .padding(.horizontal, 4)
        .background { glassCapsule() }
    }

    // MARK: - Profile Card (Desktop: ProfileCard component)

    private var profileCard: some View {
        VStack(spacing: 0) {
            AvatarView(
                initials: avatarInitials,
                colorIndex: avatarColorIndex,
                size: 100,
                isOnline: false,
                image: opponentAvatar
            )

            HStack(spacing: 5) {
                Text(displayName)
                    .font(.system(size: 22, weight: .semibold))
                    .foregroundStyle(RosettaColors.Adaptive.text)
                    .lineLimit(2)
                    .multilineTextAlignment(.center)

                if effectiveVerified > 0 {
                    VerifiedBadge(verified: effectiveVerified, size: 18, badgeTint: .white)
                }
            }
            .padding(.top, 12)
            .padding(.horizontal, 32)

            Text(subtitleText)
                .font(.system(size: 14))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .padding(.top, 4)
        }
    }

    // MARK: - Info Sections (Desktop: SettingsInput.Copy rows)

    private var infoSections: some View {
        VStack(spacing: 16) {
            if !username.isEmpty {
                copyRow(
                    label: "Username",
                    value: "@\(username)",
                    rawValue: username,
                    fieldId: "username",
                    helper: "Username for search user or send message."
                )
            }

            copyRow(
                label: "Public Key",
                value: route.publicKey,
                rawValue: route.publicKey,
                fieldId: "publicKey",
                helper: "This is user public key. If user haven't set a @username yet, you can send message using public key."
            )
        }
    }

    // MARK: - Copy Row (Desktop: SettingsInput.Copy)

    private func copyRow(
        label: String,
        value: String,
        rawValue: String,
        fieldId: String,
        helper: String
    ) -> some View {
        VStack(alignment: .leading, spacing: 6) {
            Button {
                UIPasteboard.general.string = rawValue
                withAnimation(.easeInOut(duration: 0.2)) { copiedField = fieldId }
                Task { @MainActor in
                    try? await Task.sleep(for: .seconds(1.5))
                    withAnimation(.easeInOut(duration: 0.2)) {
                        if copiedField == fieldId { copiedField = nil }
                    }
                }
            } label: {
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text(label)
                            .font(.system(size: 13))
                            .foregroundStyle(RosettaColors.Adaptive.textSecondary)

                        Text(copiedField == fieldId ? "Copied" : value)
                            .font(.system(size: 16))
                            .foregroundStyle(
                                copiedField == fieldId
                                    ? RosettaColors.online
                                    : RosettaColors.Adaptive.text
                            )
                            .lineLimit(1)
                            .truncationMode(.middle)
                    }

                    Spacer()

                    Image(systemName: copiedField == fieldId ? "checkmark" : "doc.on.doc")
                        .font(.system(size: 13))
                        .foregroundStyle(
                            copiedField == fieldId
                                ? RosettaColors.online
                                : RosettaColors.Adaptive.textSecondary
                        )
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 14)
                .background { glassCard() }
            }
            .buttonStyle(.plain)

            Text(helper)
                .font(.system(size: 12))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary.opacity(0.7))
                .padding(.horizontal, 8)
        }
    }

    // MARK: - Glass helpers

    // Use TelegramGlass* UIViewRepresentable for ALL iOS versions.
    // SwiftUI .glassEffect() creates UIKit containers that intercept taps
    // even with .allowsHitTesting(false) — breaks back button.

    private func glassCapsule() -> some View {
        TelegramGlassCapsule()
    }

    private func glassCard() -> some View {
        TelegramGlassRoundedRect(cornerRadius: 14)
    }
}
