import SwiftUI

// MARK: - GroupSetupView

/// Two-step Telegram-style group creation form.
/// Step 1: Group name (required). Step 2: Description (optional) + Create.
struct GroupSetupView: View {
    @StateObject private var viewModel = GroupSetupViewModel()
    @Environment(\.dismiss) private var dismiss

    /// Called when group is created — passes the ChatRoute for navigation.
    var onGroupCreated: ((ChatRoute) -> Void)?

    @State private var step: SetupStep = .name
    @FocusState private var isTitleFocused: Bool

    private enum SetupStep {
        case name
        case description
    }

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

            VStack(spacing: 0) {
                stepContent
            }

            if viewModel.isCreating {
                loadingOverlay
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbar { toolbarContent }
        .onChange(of: viewModel.createdRoute) { route in
            if let route {
                onGroupCreated?(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: - Step Content

private extension GroupSetupView {
    @ViewBuilder
    var stepContent: some View {
        switch step {
        case .name:
            nameStep
        case .description:
            descriptionStep
        }
    }

    var nameStep: some View {
        VStack(spacing: 24) {
            Spacer().frame(height: 20)

            // Group avatar placeholder
            ZStack {
                Circle()
                    .fill(RosettaColors.figmaBlue.opacity(0.2))
                    .frame(width: 80, height: 80)
                Image(systemName: "camera.fill")
                    .font(.system(size: 28))
                    .foregroundStyle(RosettaColors.figmaBlue)
            }

            // Group name field
            VStack(alignment: .leading, spacing: 8) {
                Text("Group Name")
                    .font(.system(size: 13, weight: .medium))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)

                TextField("Enter group name", text: $viewModel.title)
                    .font(.system(size: 17))
                    .foregroundStyle(RosettaColors.Adaptive.text)
                    .focused($isTitleFocused)
                    .onChange(of: viewModel.title) { newValue in
                        if newValue.count > GroupSetupViewModel.maxTitleLength {
                            viewModel.title = String(newValue.prefix(GroupSetupViewModel.maxTitleLength))
                        }
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 12)
                    .background {
                        GlassCard(cornerRadius: 12) {
                            Color.clear.frame(height: 44)
                        }
                    }

                Text("\(viewModel.title.count)/\(GroupSetupViewModel.maxTitleLength)")
                    .font(.system(size: 12))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                    .frame(maxWidth: .infinity, alignment: .trailing)
            }
            .padding(.horizontal, 16)

            Spacer()
        }
        .onAppear { isTitleFocused = true }
    }

    var descriptionStep: some View {
        VStack(spacing: 24) {
            Spacer().frame(height: 20)

            VStack(alignment: .leading, spacing: 8) {
                Text("Description (optional)")
                    .font(.system(size: 13, weight: .medium))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)

                TextField("Enter group description", text: $viewModel.groupDescription, axis: .vertical)
                    .font(.system(size: 17))
                    .foregroundStyle(RosettaColors.Adaptive.text)
                    .lineLimit(3...6)
                    .onChange(of: viewModel.groupDescription) { newValue in
                        if newValue.count > GroupSetupViewModel.maxDescriptionLength {
                            viewModel.groupDescription = String(
                                newValue.prefix(GroupSetupViewModel.maxDescriptionLength)
                            )
                        }
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 12)
                    .background {
                        GlassCard(cornerRadius: 12) {
                            Color.clear.frame(height: 80)
                        }
                    }

                Text("You can provide an optional description for your group.")
                    .font(.system(size: 13))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)
            }
            .padding(.horizontal, 16)

            Spacer()
        }
    }
}

// MARK: - Loading Overlay

private extension GroupSetupView {
    var loadingOverlay: some View {
        Color.black.opacity(0.4)
            .ignoresSafeArea()
            .overlay {
                ProgressView()
                    .tint(RosettaColors.Adaptive.text)
                    .scaleEffect(1.2)
            }
    }
}

// MARK: - Toolbar

private extension GroupSetupView {
    @ToolbarContentBuilder
    var toolbarContent: some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            Button {
                switch step {
                case .name: dismiss()
                case .description: step = .name
                }
            } label: {
                Text(step == .name ? "Cancel" : "Back")
                    .font(.system(size: 17, weight: .medium))
                    .foregroundStyle(RosettaColors.Adaptive.text)
            }
        }

        ToolbarItem(placement: .principal) {
            Text(step == .name ? "New Group" : "Description")
                .font(.system(size: 17, weight: .semibold))
                .foregroundStyle(RosettaColors.Adaptive.text)
        }

        ToolbarItem(placement: .navigationBarTrailing) {
            Button {
                switch step {
                case .name:
                    step = .description
                case .description:
                    Task { await viewModel.createGroup() }
                }
            } label: {
                Text(step == .name ? "Next" : "Create")
                    .font(.system(size: 17, weight: .semibold))
                    .foregroundStyle(
                        viewModel.canCreate || step == .name
                            ? RosettaColors.figmaBlue
                            : RosettaColors.Adaptive.textSecondary
                    )
            }
            .disabled(step == .name ? viewModel.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty : !viewModel.canCreate)
        }
    }
}
