import SwiftUI

struct ProfileView: View {
    @StateObject private var viewModel = ProfileViewModel()
    @Environment(\.dismiss) var dismiss
    @FocusState private var focusedField: Field?

    enum Field {
        case firstName, lastName, email
    }

    var body: some View {
        NavigationStack {
            ZStack {
                WarmGradientBackground()
                    .ignoresSafeArea()

                if viewModel.isLoadingUser {
                    VStack(spacing: OrganicSpacing.comfortable) {
                        ZStack {
                            Circle()
                                .fill(Color.appPrimary.opacity(0.1))
                                .frame(width: 64, height: 64)
                            ProgressView()
                                .scaleEffect(1.2)
                                .tint(Color.appPrimary)
                        }
                        Text(L10n.Profile.loadingProfile)
                            .font(.system(size: 15, weight: .medium, design: .rounded))
                            .foregroundColor(Color.appTextSecondary)
                    }
                } else {
                    Form {
                        Section {
                            VStack(spacing: OrganicSpacing.cozy) {
                                ZStack {
                                    Circle()
                                        .fill(
                                            RadialGradient(
                                                colors: [
                                                    Color.appPrimary.opacity(0.15),
                                                    Color.appPrimary.opacity(0.05),
                                                    Color.clear
                                                ],
                                                center: .center,
                                                startRadius: 0,
                                                endRadius: 50
                                            )
                                        )
                                        .frame(width: 100, height: 100)

                                    Image(systemName: "person.circle.fill")
                                        .font(.system(size: 56))
                                        .foregroundStyle(Color.appPrimary.gradient)
                                }

                                Text(L10n.Profile.profileSettings)
                                    .font(.system(size: 22, weight: .bold, design: .rounded))
                                    .foregroundColor(Color.appTextPrimary)
                                    .a11yHeader()
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.vertical)
                        }
                        .listRowBackground(Color.clear)

                    Section {
                        TextField(L10n.Profile.firstName, text: $viewModel.firstName)
                            .textInputAutocapitalization(.words)
                            .autocorrectionDisabled()
                            .focused($focusedField, equals: .firstName)
                            .submitLabel(.next)
                            .onSubmit {
                                focusedField = .lastName
                            }
                            .accessibilityIdentifier("Profile.FirstNameField")
                            .accessibilityHint("Enter your first name")

                        TextField(L10n.Profile.lastName, text: $viewModel.lastName)
                            .textInputAutocapitalization(.words)
                            .autocorrectionDisabled()
                            .focused($focusedField, equals: .lastName)
                            .submitLabel(.next)
                            .onSubmit {
                                focusedField = .email
                            }
                            .accessibilityIdentifier("Profile.LastNameField")
                            .accessibilityHint("Enter your last name")
                    } header: {
                        Text(L10n.Profile.personalInformation)
                    }
                    .listRowBackground(Color.appBackgroundSecondary)

                    Section {
                        TextField(L10n.Profile.email, text: $viewModel.email)
                            .textInputAutocapitalization(.never)
                            .autocorrectionDisabled()
                            .keyboardType(.emailAddress)
                            .focused($focusedField, equals: .email)
                            .submitLabel(.done)
                            .onSubmit {
                                viewModel.updateProfile()
                            }
                            .accessibilityIdentifier("Profile.EmailField")
                            .accessibilityHint("Enter your email address")
                    } header: {
                        Text(L10n.Profile.contact)
                    } footer: {
                        Text(L10n.Profile.emailRequiredUnique)
                    }
                    .listRowBackground(Color.appBackgroundSecondary)

                    if let errorMessage = viewModel.errorMessage {
                        Section {
                            HStack {
                                Image(systemName: "exclamationmark.triangle.fill")
                                    .foregroundColor(Color.appError)
                                Text(errorMessage)
                                    .foregroundColor(Color.appError)
                                    .font(.subheadline)
                            }
                        }
                        .sectionBackground()
                    }

                    if let successMessage = viewModel.successMessage {
                        Section {
                            HStack {
                                Image(systemName: "checkmark.circle.fill")
                                    .foregroundColor(Color.appPrimary)
                                Text(successMessage)
                                    .foregroundColor(Color.appPrimary)
                                    .font(.subheadline)
                            }
                        }
                        .sectionBackground()
                    }

                    Section {
                        Button(action: viewModel.updateProfile) {
                            HStack {
                                Spacer()
                                if viewModel.isLoading {
                                    ProgressView()
                                } else {
                                    Text(L10n.Profile.saveChanges)
                                        .fontWeight(.semibold)
                                }
                                Spacer()
                            }
                        }
                        .accessibilityIdentifier("Profile.SaveButton")
                        .disabled(viewModel.isLoading || viewModel.email.isEmpty)
                    }
                    .listRowBackground(Color.appBackgroundSecondary)
                }
                .listStyle(.plain)
                .scrollContentBackground(.hidden)
                .background(Color.clear)
                }
            }
            .navigationTitle(L10n.Profile.title)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(L10n.Common.cancel) {
                        dismiss()
                    }
                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                }
            }
            .onChange(of: viewModel.firstName) { _, _ in
                viewModel.clearMessages()
            }
            .onChange(of: viewModel.lastName) { _, _ in
                viewModel.clearMessages()
            }
            .onChange(of: viewModel.email) { _, _ in
                viewModel.clearMessages()
            }
            .handleErrors(
                error: viewModel.errorMessage,
                onRetry: { viewModel.updateProfile() }
            )
        }
    }
}

#Preview {
    ProfileView()
}
