import SwiftUI

// MARK: - Full-Screen Call Overlay (Telegram-style)

struct ActiveCallOverlayView: View {
    @ObservedObject var callManager: CallManager
    @State private var peerAvatar: UIImage?
    @State private var dragOffset: CGFloat = 0

    private var state: CallUiState {
        callManager.uiState
    }

    private var durationText: String {
        let duration = max(state.durationSec, 0)
        let minutes = duration / 60
        let seconds = duration % 60
        return String(format: "%d:%02d", minutes, seconds)
    }

    private var peerInitials: String {
        RosettaColors.initials(
            name: state.peerTitle.isEmpty ? state.peerUsername : state.peerTitle,
            publicKey: state.peerPublicKey
        )
    }

    private var peerColorIndex: Int {
        RosettaColors.avatarColorIndex(for: state.peerTitle, publicKey: state.peerPublicKey)
    }

    var body: some View {
        ZStack {
            // Animated gradient background (uses avatar photo colors when available)
            CallGradientBackground(colorIndex: peerColorIndex, peerAvatar: peerAvatar)

            // Content
            VStack(spacing: 0) {
                // Top bar: Back button + E2E badge
                topBar
                    .padding(.top, 12)

                Spacer()
                    .frame(minHeight: 20, maxHeight: .infinity)
                    .layoutPriority(1)

                // Avatar with pulsing rings
                avatarSection

                // Name (Telegram: 28pt regular)
                Text(state.displayName)
                    .font(.system(size: 28, weight: .regular))
                    .foregroundStyle(.white)
                    .multilineTextAlignment(.center)
                    .lineLimit(2)
                    .padding(.horizontal, 16)
                    .padding(.top, 39)

                // Status / Duration (Telegram: 15pt)
                statusSection
                    .padding(.top, 6)

                Spacer()
                    .frame(minHeight: 40, maxHeight: .infinity)
                    .layoutPriority(2)

                // Action buttons
                CallActionButtonsView(callManager: callManager)
                    .padding(.bottom, 52)
            }
        }
        .offset(y: dragOffset)
        .gesture(minimizeGesture)
        .statusBarHidden(true)
        .onAppear {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),
                                            to: nil, from: nil, for: nil)
        }
    }

    // MARK: - Top Bar

    private var topBar: some View {
        ZStack {
            // E2E badge (centered)
            HStack(spacing: 6) {
                Image(systemName: "lock.fill")
                    .font(.system(size: 12))
                Text("End-to-end Encrypted")
                    .font(.system(size: 13, weight: .medium))
            }
            .foregroundStyle(Color.white.opacity(0.5))

            // Back button (left-aligned)
            HStack {
                Button {
                    callManager.minimizeCall()
                } label: {
                    HStack(spacing: 4) {
                        Image(systemName: "chevron.left")
                            .font(.system(size: 17, weight: .semibold))
                        Text("Back")
                            .font(.system(size: 17))
                    }
                    .foregroundStyle(.white)
                    .padding(.horizontal, 10)
                    .padding(.vertical, 6)
                    .contentShape(Rectangle())
                }
                .buttonStyle(.plain)

                Spacer()
            }
        }
        .padding(.horizontal, 6)
    }

    // MARK: - Avatar (Telegram: 136pt)

    private var avatarSection: some View {
        ZStack {
            if state.phase != .active {
                CallPulsingRings(size: 136)
            }

            AvatarView(
                initials: peerInitials,
                colorIndex: peerColorIndex,
                size: 136,
                image: peerAvatar
            )
        }
        .frame(width: 250, height: 250)
        .task(id: state.peerPublicKey) {
            peerAvatar = AvatarRepository.shared.loadAvatar(publicKey: state.peerPublicKey)
        }
    }

    // MARK: - Status

    private var statusSection: some View {
        Group {
            if state.phase == .active {
                Text(durationText)
                    .font(.system(size: 15, weight: .regular).monospacedDigit())
                    .contentTransition(.numericText())
            } else {
                Text(statusText(for: state.phase))
                    .font(.system(size: 15, weight: .regular))
            }
        }
        .foregroundStyle(Color.white.opacity(0.7))
    }

    // MARK: - Swipe-to-Minimize Gesture

    private var minimizeGesture: some Gesture {
        DragGesture(minimumDistance: 30)
            .onChanged { value in
                let dy = value.translation.height
                // Only allow downward swipe
                if dy > 0 {
                    dragOffset = dy
                }
            }
            .onEnded { value in
                let dy = value.translation.height
                let velocity = value.predictedEndTranslation.height

                // Minimize if dragged > 150pt or velocity > 300pt/s
                if dy > 150 || velocity > 300 {
                    print("[CallBar] Swipe-to-minimize: dy=\(Int(dy)) velocity=\(Int(velocity))")
                    withAnimation(.spring(response: 0.4, dampingFraction: 0.85)) {
                        dragOffset = UIScreen.main.bounds.height
                    }
                    callManager.pendingMinimizeTask?.cancel()
                    callManager.pendingMinimizeTask = Task { @MainActor in
                        try? await Task.sleep(for: .seconds(0.4))
                        guard !Task.isCancelled else {
                            print("[CallBar] Swipe minimize Task cancelled (user expanded)")
                            return
                        }
                        print("[CallBar] Swipe: setting isMinimized=true (phase=\(callManager.uiState.phase.rawValue))")
                        // Animate isMinimized for MinimizedCallBar entrance transition.
                        // Don't reset dragOffset — overlay is off-screen, and @State
                        // resets to 0 when the view is re-inserted on expandCall().
                        withAnimation(.spring(response: 0.4, dampingFraction: 0.85)) {
                            callManager.uiState.isMinimized = true
                        }
                    }
                } else {
                    withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
                        dragOffset = 0
                    }
                }
            }
    }

    // MARK: - Status Text

    private func statusText(for phase: CallPhase) -> String {
        switch phase {
        case .incoming: return "Incoming call"
        case .outgoing: return "Ringing..."
        case .keyExchange: return "Exchanging keys..."
        case .webRtcExchange: return "Connecting..."
        case .active: return "Active"
        case .ended: return "Ended"
        case .idle: return ""
        }
    }
}
