import SwiftUI

// MARK: - GroupJoinView

/// Join a group by pasting an invite string.
struct GroupJoinView: View {
    @StateObject private var viewModel = GroupJoinViewModel()
    @Environment(\.dismiss) private var dismiss

    var onGroupJoined: ((ChatRoute) -> Void)?

    @FocusState private var isFieldFocused: Bool

    var body: some View {
        ZStack {
            RosettaColors.Adaptive.background.ignoresSafeArea()

            VStack(spacing: 24) {
                Spacer().frame(height: 20)

                // Invite string input
                VStack(alignment: .leading, spacing: 8) {
                    Text("Invite Link")
                        .font(.system(size: 13, weight: .medium))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)

                    TextField("Paste invite link", text: $viewModel.inviteString)
                        .font(.system(size: 15))
                        .foregroundStyle(RosettaColors.Adaptive.text)
                        .focused($isFieldFocused)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                        .onChange(of: viewModel.inviteString) { _ in
                            viewModel.parseInvite()
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                        .background {
                            GlassCard(cornerRadius: 12) {
                                Color.clear.frame(height: 44)
                            }
                        }

                    Text("Enter the group invite link shared with you.")
                        .font(.system(size: 13))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                }
                .padding(.horizontal, 16)

                // Preview card (shown after parsing)
                if viewModel.hasParsedInvite {
                    previewCard
                }

                Spacer()

                // Join button
                if viewModel.hasParsedInvite {
                    joinButton
                        .padding(.horizontal, 16)
                        .padding(.bottom, 16)
                }
            }

            if viewModel.isJoining {
                Color.black.opacity(0.4)
                    .ignoresSafeArea()
                    .overlay {
                        ProgressView()
                            .tint(RosettaColors.Adaptive.text)
                            .scaleEffect(1.2)
                    }
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button { dismiss() } label: {
                    // Telegram exact: two diagonal lines, 2pt lineWidth, round cap, inset 0.3
                    // Matches ComposeGlassCloseButton (SearchBarPlaceholderNode.swift parity)
                    Canvas { context, size in
                        let inset = min(size.width, size.height) * 0.3
                        var path = Path()
                        path.move(to: CGPoint(x: inset, y: inset))
                        path.addLine(to: CGPoint(x: size.width - inset, y: size.height - inset))
                        path.move(to: CGPoint(x: size.width - inset, y: inset))
                        path.addLine(to: CGPoint(x: inset, y: size.height - inset))
                        context.stroke(path, with: .foreground, style: StrokeStyle(lineWidth: 2, lineCap: .round))
                    }
                    .foregroundStyle(RosettaColors.Adaptive.text)
                    .frame(width: 44, height: 44)
                    .contentShape(Circle())
                    .background { TelegramGlassCapsule() }
                }
                .buttonStyle(.plain)
            }
            ToolbarItem(placement: .principal) {
                Text("Join Group")
                    .font(.system(size: 17, weight: .semibold))
                    .foregroundStyle(RosettaColors.Adaptive.text)
            }
        }
        .onAppear { isFieldFocused = true }
        .onChange(of: viewModel.joinedRoute) { route in
            if let route {
                onGroupJoined?(route)
                dismiss()
            }
        }
        .alert("Error", isPresented: .init(
            get: { viewModel.errorMessage != nil },
            set: { if !$0 { viewModel.errorMessage = nil } }
        )) {
            Button("OK", role: .cancel) {}
        } message: {
            if let msg = viewModel.errorMessage {
                Text(msg)
            }
        }
    }
}

// MARK: - Preview Card

private extension GroupJoinView {
    var previewCard: some View {
        GlassCard(cornerRadius: 16) {
            VStack(alignment: .leading, spacing: 8) {
                HStack(spacing: 12) {
                    // Group avatar (Mantine light variant)
                    let groupTitle = viewModel.parsedTitle ?? ""
                    AvatarView(
                        initials: RosettaColors.groupInitial(name: groupTitle, publicKey: ""),
                        colorIndex: RosettaColors.avatarColorIndex(for: groupTitle),
                        size: 48
                    )

                    VStack(alignment: .leading, spacing: 2) {
                        if let title = viewModel.parsedTitle {
                            Text(title)
                                .font(.system(size: 17, weight: .semibold))
                                .foregroundStyle(RosettaColors.Adaptive.text)
                        }
                        if let count = viewModel.memberCount {
                            Text("\(count) members")
                                .font(.system(size: 14))
                                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                        }
                    }

                    Spacer()

                    if viewModel.isChecking {
                        ProgressView()
                            .tint(.white)
                    }
                }

                if let desc = viewModel.parsedDescription, !desc.isEmpty {
                    Text(desc)
                        .font(.system(size: 14))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                        .lineLimit(3)
                }

                if let status = viewModel.inviteStatus {
                    statusBadge(status)
                }
            }
            .padding(16)
        }
        .padding(.horizontal, 16)
        .task { await viewModel.checkStatus() }
    }

    @ViewBuilder
    func statusBadge(_ status: GroupStatus) -> some View {
        switch status {
        case .joined:
            Label("Already a member", systemImage: "checkmark.circle.fill")
                .font(.system(size: 13, weight: .medium))
                .foregroundStyle(.green)
        case .banned:
            Label("You are banned", systemImage: "xmark.circle.fill")
                .font(.system(size: 13, weight: .medium))
                .foregroundStyle(.red)
        case .invalid:
            Label("Group not found", systemImage: "exclamationmark.circle.fill")
                .font(.system(size: 13, weight: .medium))
                .foregroundStyle(.orange)
        case .notJoined:
            EmptyView()
        }
    }
}

// MARK: - Join Button

private extension GroupJoinView {
    var joinButton: some View {
        Button {
            Task { await viewModel.joinGroup() }
        } label: {
            Text("Join Group")
                .font(.system(size: 17, weight: .semibold))
                .foregroundStyle(.white)
                .frame(maxWidth: .infinity)
                .frame(height: 50)
                .background(
                    RoundedRectangle(cornerRadius: 12, style: .continuous)
                        .fill(canJoin ? RosettaColors.figmaBlue : RosettaColors.figmaBlue.opacity(0.4))
                )
        }
        .disabled(!canJoin)
    }

    var canJoin: Bool {
        viewModel.hasParsedInvite
            && !viewModel.isJoining
            && viewModel.inviteStatus != .banned
            && viewModel.inviteStatus != .invalid
    }
}
