import SwiftUI

struct VerifyResetCodeView: View {
    @ObservedObject var viewModel: PasswordResetViewModel
    @FocusState private var isCodeFocused: Bool
    @Environment(\.dismiss) var dismiss

    var body: some View {
            ZStack {
                WarmGradientBackground()

                ScrollView(showsIndicators: false) {
                    VStack(spacing: OrganicSpacing.spacious) {
                        Spacer()
                            .frame(height: OrganicSpacing.comfortable)

                        // Hero Section
                        VStack(spacing: OrganicSpacing.comfortable) {
                            ZStack {
                                Circle()
                                    .fill(
                                        RadialGradient(
                                            colors: [
                                                Color.appPrimary.opacity(0.15),
                                                Color.appPrimary.opacity(0.05),
                                                Color.clear
                                            ],
                                            center: .center,
                                            startRadius: 0,
                                            endRadius: 60
                                        )
                                    )
                                    .frame(width: 120, height: 120)

                                Image(systemName: "envelope.badge.fill")
                                    .font(.system(size: 48, weight: .medium))
                                    .foregroundColor(Color.appPrimary)
                            }

                            VStack(spacing: 8) {
                                Text("Check Your Email")
                                    .font(.system(size: 26, weight: .bold, design: .rounded))
                                    .foregroundColor(Color.appTextPrimary)
                                    .a11yHeader()

                                Text("We sent a 6-digit code to")
                                    .font(.system(size: 15, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)

                                Text(viewModel.email)
                                    .font(.system(size: 15, weight: .bold, design: .rounded))
                                    .foregroundColor(Color.appPrimary)
                            }
                        }

                        // Form Card
                        VStack(spacing: 20) {
                            // Timer Info
                            HStack(spacing: 12) {
                                ZStack {
                                    Circle()
                                        .fill(Color.appAccent.opacity(0.1))
                                        .frame(width: 40, height: 40)
                                    Image(systemName: "clock.fill")
                                        .font(.system(size: 18, weight: .medium))
                                        .foregroundColor(Color.appAccent)
                                }

                                Text("Code expires in 15 minutes")
                                    .font(.system(size: 14, weight: .semibold))
                                    .foregroundColor(Color.appTextPrimary)

                                Spacer()
                            }
                            .padding(16)
                            .background(Color.appAccent.opacity(0.08))
                            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))

                            // Code Input
                            VStack(alignment: .leading, spacing: 8) {
                                Text("VERIFICATION CODE")
                                    .font(.system(size: 11, weight: .semibold, design: .rounded))
                                    .foregroundColor(Color.appTextSecondary)
                                    .tracking(1.2)

                                TextField("000000", text: $viewModel.code)
                                    .font(.system(size: 32, weight: .bold, design: .rounded))
                                    .multilineTextAlignment(.center)
                                    .keyboardType(.numberPad)
                                    .focused($isCodeFocused)
                                    .keyboardDismissToolbar()
                                    .accessibilityIdentifier(AccessibilityIdentifiers.PasswordReset.codeField)
                                    .accessibilityHint("Enter 6-digit verification code from your email")
                                    .padding(20)
                                    .background(Color.appBackgroundPrimary.opacity(0.5))
                                    .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 16, style: .continuous)
                                            .stroke(isCodeFocused ? Color.appPrimary : Color.appTextSecondary.opacity(0.15), lineWidth: 1.5)
                                    )
                                    .onChange(of: viewModel.code) { _, newValue in
                                        let filtered = String(newValue.filter { $0.isNumber }.prefix(6))
                                        if filtered != newValue {
                                            viewModel.code = filtered
                                        }
                                        viewModel.clearError()
                                    }

                                Text("Enter the 6-digit code from your email")
                                    .font(.system(size: 12, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)
                            }

                            // Error Message
                            if let errorMessage = viewModel.errorMessage {
                                HStack(spacing: 10) {
                                    Image(systemName: "exclamationmark.circle.fill")
                                        .foregroundColor(Color.appError)
                                    Text(errorMessage)
                                        .font(.system(size: 14, weight: .medium))
                                        .foregroundColor(Color.appError)
                                    Spacer()
                                }
                                .padding(16)
                                .background(Color.appError.opacity(0.1))
                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            }

                            // Success Message
                            if let successMessage = viewModel.successMessage {
                                HStack(spacing: 10) {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundColor(Color.appPrimary)
                                    Text(successMessage)
                                        .font(.system(size: 14, weight: .medium))
                                        .foregroundColor(Color.appPrimary)
                                    Spacer()
                                }
                                .padding(16)
                                .background(Color.appPrimary.opacity(0.1))
                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            }

                            // Verify Button
                            Button(action: {
                                viewModel.verifyResetCode()
                            }) {
                                HStack(spacing: 8) {
                                    if viewModel.isLoading {
                                        ProgressView()
                                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                    } else {
                                        Image(systemName: "checkmark.shield.fill")
                                    }
                                    Text(viewModel.isLoading ? "Verifying..." : "Verify Code")
                                        .font(.headline)
                                        .fontWeight(.semibold)
                                }
                                .frame(maxWidth: .infinity)
                                .frame(height: 56)
                                .foregroundColor(Color.appTextOnPrimary)
                                .background(
                                    viewModel.code.count == 6 && !viewModel.isLoading
                                        ? AnyShapeStyle(LinearGradient(colors: [Color.appPrimary, Color.appPrimary.opacity(0.8)], startPoint: .topLeading, endPoint: .bottomTrailing))
                                        : AnyShapeStyle(Color.appTextSecondary)
                                )
                                .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
                                .shadow(
                                    color: viewModel.code.count == 6 && !viewModel.isLoading ? Color.appPrimary.opacity(0.3) : .clear,
                                    radius: 10,
                                    y: 5
                                )
                            }
                            .disabled(viewModel.code.count != 6 || viewModel.isLoading)
                            .accessibilityIdentifier(AccessibilityIdentifiers.PasswordReset.verifyCodeButton)

                            OrganicDivider()
                                .padding(.vertical, 4)

                            // Help Section
                            VStack(spacing: 12) {
                                Text("Didn't receive the code?")
                                    .font(.system(size: 14, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)

                                Button(action: {
                                    viewModel.code = ""
                                    viewModel.clearError()
                                    viewModel.currentStep = .requestCode
                                }) {
                                    Text("Send New Code")
                                        .font(.system(size: 15, weight: .bold, design: .rounded))
                                        .foregroundColor(Color.appPrimary)
                                }
                                .accessibilityIdentifier(AccessibilityIdentifiers.PasswordReset.resendCodeButton)

                                Text("Check your spam folder if you don't see it")
                                    .font(.system(size: 12, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)
                                    .multilineTextAlignment(.center)
                            }
                        }
                        .padding(OrganicSpacing.cozy)
                        .background(OrganicVerifyCardBackground())
                        .clipShape(RoundedRectangle(cornerRadius: 32, style: .continuous))
                        .naturalShadow(.pronounced)
                        .padding(.horizontal, 16)

                        Spacer()
                    }
                }
            }
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                        viewModel.moveToPreviousStep()
                    }) {
                        HStack(spacing: 6) {
                            Image(systemName: "chevron.left")
                                .font(.system(size: 14, weight: .semibold))
                            Text("Back")
                                .font(.system(size: 15, weight: .medium))
                        }
                        .foregroundColor(Color.appPrimary)
                    }
                }
            }
            .onAppear {
                isCodeFocused = true
            }
    }
}

// MARK: - Background

private struct OrganicVerifyCardBackground: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            Color.appBackgroundSecondary

            GeometryReader { geo in
                OrganicBlobShape(variation: 1)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(colorScheme == .dark ? 0.08 : 0.05),
                                Color.appPrimary.opacity(0.01)
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.5
                        )
                    )
                    .frame(width: geo.size.width * 0.6, height: geo.size.height * 0.4)
                    .offset(x: geo.size.width * 0.45, y: geo.size.height * 0.5)
                    .blur(radius: 20)
            }

            GrainTexture(opacity: 0.015)
        }
    }
}

#Preview {
    let vm = PasswordResetViewModel()
    vm.email = "test@example.com"
    vm.currentStep = .verifyCode
    return VerifyResetCodeView(viewModel: vm)
}
