//
//  AddMemberSheet.swift
//  DeskHive
//
//  Modal bottom sheet that lets an admin register a new member by email.
//  A secure random password is generated by a Cloud Function on the backend
//  and delivered to the new member via email — it is never stored in plain text
//  or exposed to the client.
//

import SwiftUI

struct AddMemberSheet: View {
    // Shared AdminViewModel so the parent's member list updates immediately after creation
    @ObservedObject var adminVM: AdminViewModel
    @Environment(\.dismiss) private var dismiss

    // Local text field binding — cleared on successful account creation
    @State private var email: String = ""

    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(colors: [Color(hex: "#1A1A2E"), Color(hex: "#0F3460")]),
                startPoint: .top,
                endPoint: .bottom
            )
            .ignoresSafeArea()

            VStack(spacing: 28) {
                // Drag handle — visual affordance that the sheet can be swiped away
                RoundedRectangle(cornerRadius: 3)
                    .fill(Color.white.opacity(0.3))
                    .frame(width: 40, height: 5)
                    .padding(.top, 12)

                // Header section — icon, title, and helper text
                VStack(spacing: 10) {
                    ZStack {
                        Circle()
                            .fill(Color(hex: "#E94560").opacity(0.2))
                            .frame(width: 70, height: 70)
                        Image(systemName: "person.badge.plus")
                            .font(.system(size: 28))
                            .foregroundColor(Color(hex: "#E94560"))
                    }

                    Text("Add New Member")
                        .font(.system(size: 22, weight: .bold, design: .rounded))
                        .foregroundColor(.white)

                    Text("A secure password will be auto-generated\nand emailed to the member.")
                        .font(.system(size: 13))
                        .foregroundColor(.white.opacity(0.6))
                        .multilineTextAlignment(.center)
                        .lineSpacing(4)
                }

                // Security notice — reassures the admin that passwords are handled safely
                HStack(spacing: 8) {
                    Image(systemName: "lock.shield.fill")
                        .foregroundColor(Color(hex: "#4ECDC4"))
                        .font(.system(size: 16))
                    Text("Password is securely generated via Cloud Function and never stored in plain text.")
                        .font(.system(size: 12))
                        .foregroundColor(.white.opacity(0.7))
                }
                .padding(14)
                .background(Color(hex: "#4ECDC4").opacity(0.1))
                .cornerRadius(12)
                .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color(hex: "#4ECDC4").opacity(0.3), lineWidth: 1))
                .padding(.horizontal, 24)

                // Input form and action buttons
                VStack(spacing: 16) {
                    DeskHiveTextField(
                        placeholder: "Member's email address",
                        text: $email,
                        icon: "envelope"
                    )
                    .keyboardType(.emailAddress)

                    // Show inline error or success feedback from the view-model
                    if let error = adminVM.errorMessage {
                        ErrorBanner(message: error)
                    }

                    if let success = adminVM.successMessage {
                        SuccessBanner(message: success)
                    }

                    PrimaryButton(title: "Create Member Account", isLoading: adminVM.isAddingMember) {
                        Task {
                            await adminVM.addMember(email: email)
                            // On success: clear the field and auto-dismiss after a short delay
                            if adminVM.successMessage != nil {
                                email = ""
                                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                    dismiss()
                                }
                            }
                        }
                    }

                    Button("Cancel") {
                        dismiss()
                    }
                    .font(.system(size: 15, weight: .medium))
                    .foregroundColor(.white.opacity(0.5))
                }
                .padding(.horizontal, 24)

                Spacer()
            }
        }
        .onAppear {
            // Reset stale messages from a previous presentation before the sheet is shown
            adminVM.errorMessage = nil
            adminVM.successMessage = nil
        }
    }
}
