import Lottie
import SwiftUI

/// Screen showing incoming message requests — opened from the "Request Chats"
/// row at the top of the main chat list (Telegram Archive style).
struct RequestChatsView: View {
    @ObservedObject var viewModel: ChatListViewModel
    @ObservedObject var navigationState: ChatListNavigationState
    @Environment(\.dismiss) private var dismiss

    /// Desktop parity: track typing dialogs from MessageRepository (@Published).
    @State private var typingDialogs: [String: Set<String>] = [:]

    var body: some View {
        Group {
            if viewModel.requestsModeDialogs.isEmpty {
                RequestsEmptyStateView()
            } else {
                List {
                    ForEach(Array(viewModel.requestsModeDialogs.enumerated()), id: \.element.id) { index, dialog in
                        requestRow(dialog, isFirst: index == 0)
                    }

                    Color.clear.frame(height: 80)
                        .listRowInsets(EdgeInsets())
                        .listRowBackground(Color.clear)
                        .listRowSeparator(.hidden)
                }
                .listStyle(.plain)
                .scrollContentBackground(.hidden)
                .scrollIndicators(.hidden)
            }
        }
        .background(RosettaColors.Adaptive.background.ignoresSafeArea())
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button { dismiss() } label: {
                    backCapsuleLabel
                }
                .buttonStyle(.plain)
            }

            ToolbarItem(placement: .principal) {
                Text("Request Chats")
                    .font(.system(size: 17, weight: .semibold))
                    .foregroundStyle(RosettaColors.Adaptive.text)
            }
        }
        .modifier(ChatListToolbarBackgroundModifier())
        .enableSwipeBack()
        .onReceive(MessageRepository.shared.$typingDialogs) { typingDialogs = $0 }
    }

    // MARK: - Capsule Back Button (matches ChatDetailView)

    private var backCapsuleLabel: 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(strokeOpacity: 0.22, strokeColor: .white)
        }
    }

    // Use TelegramGlass* for ALL iOS versions — SwiftUI .glassEffect() blocks touches.
    private func glassCapsule(strokeOpacity: Double = 0.18, strokeColor: Color = .white) -> some View {
        TelegramGlassCapsule()
    }

    private func requestRow(_ dialog: Dialog, isFirst: Bool) -> some View {
        SyncAwareChatRow(
            dialog: dialog,
            isTyping: !(typingDialogs[dialog.opponentKey]?.isEmpty ?? true),
            typingSenderNames: {
                guard let senderKeys = typingDialogs[dialog.opponentKey] else { return [] }
                return senderKeys.map { sk in
                    DialogRepository.shared.dialogs[sk]?.opponentTitle
                        ?? String(sk.prefix(8))
                }
            }(),
            isFirst: isFirst,
            viewModel: viewModel,
            navigationState: navigationState
        )
    }
}

// MARK: - Requests Empty State

/// Shown when there are no incoming requests.
/// Design: folder Lottie + title + subtitle.
private struct RequestsEmptyStateView: View {
    var body: some View {
        VStack(spacing: 0) {
            LottieView(animationName: "folder_empty", loopMode: .playOnce, animationSpeed: 1.0)
                .frame(width: 150, height: 150)

            Spacer().frame(height: 24)

            Text("No Requests")
                .font(.system(size: 18, weight: .semibold))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .multilineTextAlignment(.center)

            Spacer().frame(height: 8)

            Text("New message requests will appear here")
                .font(.system(size: 15))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .multilineTextAlignment(.center)
                .padding(.horizontal, 40)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .offset(y: -40)
    }
}
