import SwiftUI

// MARK: - GroupEditView

/// Telegram-parity group edit screen. All colors adaptive for light/dark.
/// Currently local-only — no server packet for group metadata updates yet.
struct GroupEditView: View {
    let groupDialogKey: String
    let initialTitle: String
    let initialDescription: String

    @Environment(\.dismiss) private var dismiss

    @State private var title: String
    @State private var description: String
    @FocusState private var focusedField: Field?

    var onSave: ((String, String) -> Void)?

    /// Telegram accent blue (#3e88f7) — same on both themes.
    private let accentBlue = Color(hex: 0x3e88f7)

    private enum Field { case title, description }

    init(
        groupDialogKey: String,
        initialTitle: String,
        initialDescription: String,
        onSave: ((String, String) -> Void)? = nil
    ) {
        self.groupDialogKey = groupDialogKey
        self.initialTitle = initialTitle
        self.initialDescription = initialDescription
        self.onSave = onSave
        _title = State(initialValue: initialTitle)
        _description = State(initialValue: initialDescription)
    }

    private var hasChanges: Bool {
        title != initialTitle || description != initialDescription
    }

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

                ScrollView {
                    VStack(spacing: 0) {
                        avatarSection
                            .padding(.top, 24)

                        fieldsSection
                            .padding(.top, 24)

                        Spacer(minLength: 40)
                    }
                }
                .scrollIndicators(.hidden)
            }
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button { dismiss() } label: {
                        Text("Cancel")
                            .font(.system(size: 17, weight: .medium))
                            .foregroundStyle(RosettaColors.Adaptive.text)
                            .padding(.horizontal, 12)
                            .frame(height: 44)
                            .background { TelegramGlassCapsule() }
                    }
                    .buttonStyle(.plain)
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button { save() } label: {
                        Text("Done")
                            .font(.system(size: 17, weight: .semibold))
                            .foregroundStyle(hasChanges ? accentBlue : RosettaColors.Adaptive.textSecondary)
                            .padding(.horizontal, 12)
                            .frame(height: 44)
                            .background { TelegramGlassCapsule() }
                    }
                    .buttonStyle(.plain)
                    .disabled(!hasChanges)
                }
            }
            .toolbarBackground(.hidden, for: .navigationBar)
        }
    }

    // MARK: - Avatar Section

    private var avatarSection: some View {
        VStack(spacing: 12) {
            ZStack {
                AvatarView(
                    initials: RosettaColors.initials(name: title.isEmpty ? initialTitle : title, publicKey: groupDialogKey),
                    colorIndex: RosettaColors.avatarColorIndex(for: title.isEmpty ? initialTitle : title, publicKey: groupDialogKey),
                    size: 100,
                    isOnline: false,
                    isSavedMessages: false
                )
                .opacity(0.6)

                Image(systemName: "camera.fill")
                    .font(.system(size: 28))
                    .foregroundStyle(accentBlue)
            }

            Text("Set New Photo")
                .font(.system(size: 17))
                .foregroundStyle(accentBlue)
        }
    }

    // MARK: - Fields Section

    private var fieldsSection: some View {
        TelegramSectionCard {
            VStack(spacing: 0) {
                // Title — 15pt vertical padding
                TextField("", text: $title, prompt: Text("Group Name").foregroundStyle(telegramPlaceholderColor))
                    .font(.system(size: 17))
                    .foregroundStyle(RosettaColors.Adaptive.text)
                    .focused($focusedField, equals: .title)
                    .padding(.horizontal, 16)
                    .padding(.vertical, 15)
                    .onSubmit { focusedField = .description }

                // Separator
                Rectangle()
                    .fill(telegramSeparatorColor)
                    .frame(height: 1.0 / UIScreen.main.scale)
                    .padding(.leading, 16)

                // Description — 255 char limit
                ZStack(alignment: .topLeading) {
                    if description.isEmpty {
                        Text("Description")
                            .font(.system(size: 17))
                            .foregroundStyle(telegramPlaceholderColor)
                            .padding(.horizontal, 16)
                            .padding(.vertical, 15)
                    }
                    TextEditor(text: $description)
                        .font(.system(size: 17))
                        .foregroundStyle(RosettaColors.Adaptive.text)
                        .scrollContentBackground(.hidden)
                        .focused($focusedField, equals: .description)
                        .padding(.horizontal, 12)
                        .padding(.vertical, 7)
                        .frame(minHeight: 44)
                        .onChange(of: description) { newValue in
                            if newValue.count > 255 {
                                description = String(newValue.prefix(255))
                            }
                        }
                }
            }
        }
        .padding(.horizontal, 16)
    }

    // MARK: - Save

    private func save() {
        let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedTitle.isEmpty else { return }

        let account = SessionManager.shared.currentPublicKey
        GroupRepository.shared.updateGroupMetadata(
            account: account,
            groupDialogKey: groupDialogKey,
            title: trimmedTitle,
            description: description.trimmingCharacters(in: .whitespacesAndNewlines)
        )
        onSave?(trimmedTitle, description.trimmingCharacters(in: .whitespacesAndNewlines))
        dismiss()
    }
}
