import SwiftUI

// MARK: - GroupInfoView

/// Telegram-style group detail screen: header, members, invite link, leave.
struct GroupInfoView: View {
    @StateObject private var viewModel: GroupInfoViewModel
    @Environment(\.dismiss) private var dismiss

    @State private var showLeaveAlert = false
    @State private var memberToKick: GroupMember?

    init(groupDialogKey: String) {
        _viewModel = StateObject(wrappedValue: GroupInfoViewModel(groupDialogKey: groupDialogKey))
    }

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

            ScrollView {
                VStack(spacing: 16) {
                    headerSection
                    if !viewModel.groupDescription.isEmpty {
                        descriptionSection
                    }
                    inviteLinkSection
                    membersSection
                    leaveSection
                }
                .padding(.vertical, 16)
            }

            if viewModel.isLeaving {
                Color.black.opacity(0.5)
                    .ignoresSafeArea()
                    .overlay {
                        ProgressView().tint(.white).scaleEffect(1.2)
                    }
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .principal) {
                Text("Group Info")
                    .font(.system(size: 17, weight: .semibold))
                    .foregroundStyle(RosettaColors.Adaptive.text)
            }
        }
        .task { await viewModel.loadMembers() }
        .onChange(of: viewModel.didLeaveGroup) { left in
            if left { dismiss() }
        }
        .alert("Leave Group", isPresented: $showLeaveAlert) {
            Button("Leave", role: .destructive) {
                Task { await viewModel.leaveGroup() }
            }
            Button("Cancel", role: .cancel) {}
        } message: {
            Text("Are you sure you want to leave this group? You will lose access to all messages.")
        }
        .alert("Remove Member", isPresented: .init(
            get: { memberToKick != nil },
            set: { if !$0 { memberToKick = nil } }
        )) {
            Button("Remove", role: .destructive) {
                if let member = memberToKick {
                    Task { await viewModel.kickMember(publicKey: member.id) }
                }
                memberToKick = nil
            }
            Button("Cancel", role: .cancel) { memberToKick = nil }
        } message: {
            if let member = memberToKick {
                Text("Remove \(member.title) from this group?")
            }
        }
        .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: - Sections

private extension GroupInfoView {
    var headerSection: some View {
        VStack(spacing: 12) {
            // Group avatar
            ZStack {
                Circle()
                    .fill(RosettaColors.figmaBlue.opacity(0.2))
                    .frame(width: 90, height: 90)
                Image(systemName: "person.2.fill")
                    .font(.system(size: 36))
                    .foregroundStyle(RosettaColors.figmaBlue)
            }

            Text(viewModel.groupTitle)
                .font(.system(size: 22, weight: .bold))
                .foregroundStyle(RosettaColors.Adaptive.text)

            Text("\(viewModel.members.count) members")
                .font(.system(size: 15))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 8)
    }

    var descriptionSection: some View {
        GlassCard(cornerRadius: 16) {
            VStack(alignment: .leading, spacing: 4) {
                Text("Description")
                    .font(.system(size: 13, weight: .medium))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                Text(viewModel.groupDescription)
                    .font(.system(size: 15))
                    .foregroundStyle(RosettaColors.Adaptive.text)
            }
            .padding(16)
            .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(.horizontal, 16)
    }

    var inviteLinkSection: some View {
        GlassCard(cornerRadius: 16) {
            VStack(alignment: .leading, spacing: 12) {
                Text("Invite Link")
                    .font(.system(size: 13, weight: .medium))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)

                if let invite = viewModel.inviteString {
                    Text(invite)
                        .font(.system(size: 13, design: .monospaced))
                        .foregroundStyle(RosettaColors.Adaptive.text)
                        .lineLimit(2)

                    HStack(spacing: 12) {
                        Button {
                            UIPasteboard.general.string = invite
                        } label: {
                            Label("Copy", systemImage: "doc.on.doc")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundStyle(RosettaColors.figmaBlue)
                        }
                    }
                } else {
                    Button {
                        viewModel.generateInvite()
                    } label: {
                        Label("Generate Link", systemImage: "link")
                            .font(.system(size: 14, weight: .medium))
                            .foregroundStyle(RosettaColors.figmaBlue)
                    }
                }
            }
            .padding(16)
            .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(.horizontal, 16)
    }

    var membersSection: some View {
        GlassCard(cornerRadius: 16) {
            VStack(alignment: .leading, spacing: 0) {
                Text("Members (\(viewModel.members.count))")
                    .font(.system(size: 13, weight: .medium))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                    .padding(.horizontal, 16)
                    .padding(.top, 16)
                    .padding(.bottom, 8)

                if viewModel.isLoading {
                    HStack {
                        Spacer()
                        ProgressView().tint(.white)
                        Spacer()
                    }
                    .padding(.vertical, 20)
                } else {
                    ForEach(viewModel.members) { member in
                        memberRow(member)
                    }
                }
            }
        }
        .padding(.horizontal, 16)
    }

    @ViewBuilder
    func memberRow(_ member: GroupMember) -> some View {
        let myKey = SessionManager.shared.currentPublicKey
        let canKick = viewModel.isAdmin && member.id != myKey && !member.isAdmin

        GroupMemberRow(member: member)
            .padding(.horizontal, 16)
            .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                if canKick {
                    Button(role: .destructive) {
                        memberToKick = member
                    } label: {
                        Label("Remove", systemImage: "person.badge.minus")
                    }
                }
            }
    }

    var leaveSection: some View {
        Button {
            showLeaveAlert = true
        } label: {
            HStack {
                Image(systemName: "rectangle.portrait.and.arrow.right")
                Text("Leave Group")
            }
            .font(.system(size: 17, weight: .medium))
            .foregroundStyle(.red)
            .frame(maxWidth: .infinity)
            .padding(.vertical, 14)
        }
        .background {
            GlassCard(cornerRadius: 16) {
                Color.clear.frame(height: 50)
            }
        }
        .padding(.horizontal, 16)
    }
}
