import SwiftUI

/// Telegram-style forward picker sheet.
/// Two modes: single-tap (immediate forward) and multi-select (checkboxes + send button).
struct ForwardChatPickerView: View {
    let onSelect: ([ChatRoute]) -> Void
    @Environment(\.dismiss) private var dismiss
    @State private var searchText = ""
    @State private var isMultiSelect = false
    @State private var selectedIds: Set<String> = []

    /// Filtered + sorted dialogs: Saved Messages always first, then pinned, then recent.
    private var dialogs: [Dialog] {
        let all = DialogRepository.shared.sortedDialogs.filter {
            ($0.iHaveSent || $0.isSavedMessages) && !SystemAccounts.isSystemAccount($0.opponentKey)
        }

        let filtered: [Dialog]
        if searchText.trimmingCharacters(in: .whitespaces).isEmpty {
            filtered = all
        } else {
            let query = searchText.lowercased()
            filtered = all.filter { dialog in
                dialog.opponentTitle.lowercased().contains(query) ||
                dialog.opponentUsername.lowercased().contains(query) ||
                (dialog.isSavedMessages && "saved messages".contains(query))
            }
        }

        var saved: Dialog?
        var rest: [Dialog] = []
        for dialog in filtered {
            if dialog.isSavedMessages {
                saved = dialog
            } else {
                rest.append(dialog)
            }
        }
        if let saved { return [saved] + rest }
        return rest
    }

    var body: some View {
        ZStack {
            RosettaColors.Adaptive.background.ignoresSafeArea()
            VStack(spacing: 0) {
                // MARK: - Header
                ForwardPickerHeader(
                    isMultiSelect: isMultiSelect,
                    onClose: { dismiss() },
                    onSelect: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            isMultiSelect = true
                        }
                    }
                )

                // MARK: - Search
                ForwardPickerSearchBar(searchText: $searchText)
                    .padding(.horizontal, 8)
                    .padding(.top, 8)
                    .padding(.bottom, 6)

                // MARK: - Chat List
                if dialogs.isEmpty && !searchText.isEmpty {
                    VStack {
                        Spacer()
                        Text("No chats found")
                            .font(.system(size: 15))
                            .foregroundStyle(Color(white: 0.5))
                        Spacer()
                    }
                } else {
                    ScrollView {
                        LazyVStack(spacing: 0) {
                            ForEach(Array(dialogs.enumerated()), id: \.element.id) { index, dialog in
                                ForwardPickerRow(
                                    dialog: dialog,
                                    isMultiSelect: isMultiSelect,
                                    isSelected: selectedIds.contains(dialog.opponentKey)
                                ) {
                                    if isMultiSelect {
                                        withAnimation(.easeInOut(duration: 0.15)) {
                                            if selectedIds.contains(dialog.opponentKey) {
                                                selectedIds.remove(dialog.opponentKey)
                                            } else {
                                                selectedIds.insert(dialog.opponentKey)
                                            }
                                        }
                                    } else {
                                        onSelect([ChatRoute(dialog: dialog)])
                                    }
                                }

                                if index < dialogs.count - 1 {
                                    Divider()
                                        .padding(.leading, 65)
                                        .foregroundStyle(Color(red: 0x54 / 255.0, green: 0x54 / 255.0, blue: 0x58 / 255.0).opacity(0.55))
                                }
                            }
                        }
                    }
                    .scrollDismissesKeyboard(.interactively)
                }

                // MARK: - Bottom Bar (multi-select)
                if isMultiSelect {
                    ForwardPickerBottomBar(
                        selectedCount: selectedIds.count,
                        onSend: {
                            let routes = dialogs
                                .filter { selectedIds.contains($0.opponentKey) }
                                .map { ChatRoute(dialog: $0) }
                            if !routes.isEmpty { onSelect(routes) }
                        }
                    )
                    .transition(.move(edge: .bottom).combined(with: .opacity))
                }
            }
        }
        .presentationBackground(RosettaColors.Adaptive.background)
        .presentationDragIndicator(.hidden)
        .presentationDetents([.large])
    }
}

// MARK: - Telegram Icons (CoreGraphics-exact replicas)

/// Telegram X close icon: two diagonal lines, 2pt stroke, round cap.
/// Source: PresentationResourcesChat.swift:215
private struct TelegramCloseIcon: Shape {
    func path(in rect: CGRect) -> Path {
        var p = Path()
        let inset: CGFloat = 1.0
        p.move(to: CGPoint(x: inset, y: inset))
        p.addLine(to: CGPoint(x: rect.width - inset, y: rect.height - inset))
        p.move(to: CGPoint(x: rect.width - inset, y: inset))
        p.addLine(to: CGPoint(x: inset, y: rect.height - inset))
        return p
    }
}

/// Telegram send arrow: arrowhead + vertical stem.
/// Source: PresentationResourcesChat.swift:365 (SVG paths)
private struct TelegramSendArrow: Shape {
    func path(in rect: CGRect) -> Path {
        let sx = rect.width / 33.0
        let sy = rect.height / 33.0
        var p = Path()
        // Arrowhead (V pointing up)
        p.move(to: CGPoint(x: 11 * sx, y: 14.667 * sy))
        p.addLine(to: CGPoint(x: 16.5 * sx, y: 9.4 * sy))
        p.addLine(to: CGPoint(x: 22 * sx, y: 14.667 * sy))
        // Stem (vertical rounded rect)
        p.addRoundedRect(
            in: CGRect(x: 15.5 * sx, y: 9.333 * sy, width: 2 * sx, height: 15.667 * sy),
            cornerSize: CGSize(width: 1 * sx, height: 1 * sy)
        )
        return p
    }
}

/// Telegram checkmark: L-shaped path, 1.5pt stroke, round cap/join.
/// Source: CheckNode.swift:468-600
private struct TelegramCheckmark: Shape {
    func path(in rect: CGRect) -> Path {
        let scale = min(rect.width, rect.height) / 18.0
        let cx = rect.midX
        let cy = rect.midY
        let start = CGPoint(x: cx - 3.5 * scale, y: cy + 0.5 * scale)
        var p = Path()
        p.move(to: start)
        p.addLine(to: CGPoint(x: start.x + 2.5 * scale, y: start.y + 3.0 * scale))
        p.addLine(to: CGPoint(x: start.x + 2.5 * scale + 4.667 * scale, y: start.y + 3.0 * scale - 6.0 * scale))
        return p
    }
}

// MARK: - Header

private struct ForwardPickerHeader: View {
    let isMultiSelect: Bool
    let onClose: () -> Void
    let onSelect: () -> Void

    var body: some View {
        ZStack {
            HStack {
                // Telegram close button: 30pt dark circle + 12x12 X icon
                Button(action: onClose) {
                    ZStack {
                        Circle()
                            .fill(Color(white: 0.16))
                            .frame(width: 30, height: 30)
                        TelegramCloseIcon()
                            .stroke(.white, style: StrokeStyle(lineWidth: 2, lineCap: .round))
                            .frame(width: 12, height: 12)
                    }
                }
                Spacer()
            }

            Text("Forward")
                .font(.system(size: 17, weight: .semibold))
                .foregroundStyle(.white)

            if !isMultiSelect {
                HStack {
                    Spacer()
                    Button(action: onSelect) {
                        Text("Select")
                            .font(.system(size: 17, weight: .regular))
                            .foregroundStyle(.white)
                            .padding(.horizontal, 14)
                            .frame(height: 30)
                            .background {
                                Capsule()
                                    .fill(Color(white: 0.16))
                            }
                    }
                }
            }
        }
        .padding(.horizontal, 16)
        .frame(height: 52)
    }
}

// MARK: - Search Bar

private struct ForwardPickerSearchBar: View {
    @Binding var searchText: String
    @FocusState private var isFocused: Bool

    var body: some View {
        HStack(spacing: 8) {
            Image(systemName: "magnifyingglass")
                .font(.system(size: 16, weight: .medium))
                .foregroundStyle(Color(white: 0.56))

            ZStack(alignment: .leading) {
                if searchText.isEmpty {
                    Text("Search")
                        .font(.system(size: 17))
                        .foregroundStyle(Color(white: 0.56))
                }
                TextField("", text: $searchText)
                    .font(.system(size: 17))
                    .foregroundStyle(.white)
                    .focused($isFocused)
                    .submitLabel(.search)
            }

            if !searchText.isEmpty {
                Button {
                    searchText = ""
                } label: {
                    Image(systemName: "xmark.circle.fill")
                        .font(.system(size: 16))
                        .foregroundStyle(Color(white: 0.56))
                }
            }
        }
        .padding(.horizontal, 14)
        .frame(height: 44)
        .background {
            RoundedRectangle(cornerRadius: 22, style: .continuous)
                .fill(Color.white.opacity(0.1))
        }
    }
}

// MARK: - Row

private struct ForwardPickerRow: View {
    let dialog: Dialog
    let isMultiSelect: Bool
    let isSelected: Bool
    let onTap: () -> Void

    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 10) {
                ForwardPickerRowAvatar(dialog: dialog)

                HStack(spacing: 4) {
                    Text(dialog.isSavedMessages ? "Saved Messages" : dialog.opponentTitle)
                        .font(.system(size: 17, weight: .medium))
                        .foregroundStyle(.white)
                        .lineLimit(1)

                    if dialog.effectiveVerified > 0 && !dialog.isSavedMessages {
                        VerifiedBadge(verified: dialog.effectiveVerified, size: 16)
                    }
                }

                Spacer()

                if isMultiSelect {
                    SelectionCircle(isSelected: isSelected)
                }
            }
            .padding(.leading, 15).padding(.trailing, 16)
            .frame(height: 48)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
    }
}

// MARK: - Row Avatar (observation-isolated)

private struct ForwardPickerRowAvatar: View {
    let dialog: Dialog

    var body: some View {
        let _ = AvatarRepository.shared.avatarVersion
        AvatarView(
            initials: dialog.initials,
            colorIndex: dialog.avatarColorIndex,
            size: 40,
            isSavedMessages: dialog.isSavedMessages,
            image: dialog.isSavedMessages ? nil : AvatarRepository.shared.loadAvatar(publicKey: dialog.opponentKey)
        )
    }
}

// MARK: - Selection Circle (Telegram CheckNode replica)

private struct SelectionCircle: View {
    let isSelected: Bool

    var body: some View {
        ZStack {
            if isSelected {
                Circle()
                    .fill(RosettaColors.primaryBlue)
                    .frame(width: 22, height: 22)
                TelegramCheckmark()
                    .stroke(.white, style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
                    .frame(width: 22, height: 22)
            } else {
                Circle()
                    .stroke(Color(white: 0.35), lineWidth: 1.5)
                    .frame(width: 22, height: 22)
            }
        }
    }
}

// MARK: - Bottom Bar

private struct ForwardPickerBottomBar: View {
    let selectedCount: Int
    let onSend: () -> Void

    var body: some View {
        VStack(spacing: 0) {
            Rectangle()
                .fill(Color(white: 0.2))
                .frame(height: 0.5)

            HStack(spacing: 10) {
                HStack(spacing: 8) {
                    Text("Message")
                        .font(.system(size: 17))
                        .foregroundStyle(Color(white: 0.35))
                    Spacer()
                }
                .padding(.horizontal, 16)
                .frame(height: 42)
                .background {
                    RoundedRectangle(cornerRadius: 21, style: .continuous)
                        .fill(Color.white.opacity(0.1))
                }

                // Telegram send button: 33pt circle + SVG arrow
                Button(action: onSend) {
                    ZStack {
                        Circle()
                            .fill(selectedCount > 0
                                  ? RosettaColors.primaryBlue
                                  : Color(white: 0.2))
                            .frame(width: 33, height: 33)
                        TelegramSendArrow()
                            .fill(.white)
                            .frame(width: 33, height: 33)
                    }
                }
                .disabled(selectedCount == 0)
            }
            .padding(.horizontal, 10)
            .padding(.vertical, 8)
        }
        .background(RosettaColors.Adaptive.background)
    }
}
