//
//  ForgotPasswordView.swift
//  AppClientBaseSwift
//
//  Forgot password screen view - Pastel Yellow Theme
//  View màn hình quên mật khẩu - Theme Pastel Vàng
//

import SwiftUI
import Combine

// MARK: - Forgot Password View
// View Quên mật khẩu

/// Forgot password screen with email reset
/// Màn hình quên mật khẩu với reset email
struct ForgotPasswordView: View {

    // MARK: - Properties

    /// Auth view model
    /// ViewModel Auth
    @ObservedObject var viewModel: AuthViewModel

    /// Focus state for email field
    /// State focus cho field email
    @FocusState private var isEmailFocused: Bool

    // MARK: - Body

    var body: some View {
        ScrollView {
            VStack(spacing: DesignSystem.spacingXL) {
                // Back button + Header
                headerSection
                    .padding(.top, 20)

                // Illustration
                illustrationSection
                    .padding(.top, DesignSystem.spacingLG)

                // Form
                formSection
                    .padding(.horizontal, DesignSystem.spacingLG)

                // Reset button
                resetButton
                    .padding(.horizontal, DesignSystem.spacingLG)

                // Back to login link
                backSection
                    .padding(.top, DesignSystem.spacingMD)

                Spacer(minLength: 40)
            }
        }
        .scrollDismissesKeyboard(.interactively)
        .alert("Lỗi", isPresented: .init(
            get: { viewModel.errorMessage != nil },
            set: { if !$0 { viewModel.errorMessage = nil } }
        )) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(viewModel.errorMessage ?? "")
        }
        .alert("Thành công", isPresented: .init(
            get: { viewModel.successMessage != nil },
            set: { if !$0 { viewModel.successMessage = nil } }
        )) {
            Button("OK") {
                viewModel.navigateTo(.login)
            }
        } message: {
            Text(viewModel.successMessage ?? "")
        }
    }

    // MARK: - Subviews

    /// Header with back button and title
    /// Header với nút back và tiêu đề
    private var headerSection: some View {
        VStack(spacing: DesignSystem.spacingLG) {
            // Back button
            HStack {
                Button {
                    viewModel.navigateTo(.login)
                } label: {
                    HStack(spacing: DesignSystem.spacingXS) {
                        Image(systemName: "chevron.left")
                        Text("Quay lại")
                    }
                    .font(.subheadline)
                    .foregroundStyle(Color.textSecondary)
                }
                Spacer()
            }
            .padding(.horizontal, DesignSystem.spacingLG)

            // Title
            VStack(spacing: DesignSystem.spacingXS) {
                Text("Quên mật khẩu?")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundStyle(Color.textPrimary)

                Text("Nhập email để nhận link đặt lại")
                    .font(.subheadline)
                    .foregroundStyle(Color.textSecondary)
            }
        }
    }

    /// Illustration section
    /// Phần minh họa
    private var illustrationSection: some View {
        ZStack {
            // Background circle
            Circle()
                .fill(
                    RadialGradient(
                        colors: [
                            Color.brandPrimary.opacity(0.3),
                            Color.clear
                        ],
                        center: .center,
                        startRadius: 20,
                        endRadius: 80
                    )
                )
                .frame(width: 160, height: 160)

            // Icon
            ZStack {
                Circle()
                    .fill(AppTheme.primaryGradient)
                    .frame(width: 100, height: 100)

                Image(systemName: "envelope.open.fill")
                    .font(.system(size: 40))
                    .foregroundStyle(Color.textPrimary)
            }
            .shadow(color: AppTheme.cardShadow, radius: 20, x: 0, y: 10)
        }
    }

    /// Form with email field
    /// Form với field email
    private var formSection: some View {
        VStack(spacing: DesignSystem.spacingMD) {
            AuthTextField(
                icon: "envelope.fill",
                placeholder: "Email",
                text: $viewModel.forgotEmail,
                keyboardType: .emailAddress
            )
            .focused($isEmailFocused)
            .submitLabel(.go)
            .onSubmit { sendResetLink() }

            // Help text
            Text("Chúng tôi sẽ gửi link đặt lại mật khẩu đến email của bạn.")
                .font(.caption)
                .foregroundStyle(Color.textSecondary)
                .multilineTextAlignment(.center)
        }
    }

    /// Reset password button
    /// Nút đặt lại mật khẩu
    private var resetButton: some View {
        Button(action: sendResetLink) {
            HStack(spacing: DesignSystem.spacingSM) {
                Text("Gửi link đặt lại")
                    .fontWeight(.semibold)

                Image(systemName: "paperplane.fill")
            }
            .font(.headline)
            .foregroundStyle(Color.textPrimary)
            .frame(maxWidth: .infinity)
            .padding(.vertical, DesignSystem.spacingMD)
            .background(
                Group {
                    if viewModel.isForgotPasswordValid {
                        AppTheme.warmGradient
                    } else {
                        LinearGradient(
                            colors: [Color.gray.opacity(0.3), Color.gray.opacity(0.2)],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    }
                }
            )
            .cornerRadius(DesignSystem.cornerRadiusMD)
            .shadow(
                color: viewModel.isForgotPasswordValid ? AppTheme.buttonShadow : .clear,
                radius: 15,
                x: 0,
                y: 8
            )
        }
        .disabled(!viewModel.isForgotPasswordValid)
    }

    /// Back to login section
    /// Phần quay lại đăng nhập
    private var backSection: some View {
        Button {
            viewModel.navigateTo(.login)
        } label: {
            HStack(spacing: DesignSystem.spacingXS) {
                Image(systemName: "arrow.left")
                Text("Quay lại đăng nhập")
            }
            .font(.subheadline)
            .foregroundStyle(Color.brandAccent)
        }
    }

    // MARK: - Methods

    /// Send reset link
    /// Gửi link đặt lại
    private func sendResetLink() {
        isEmailFocused = false
        Task {
            await viewModel.forgotPassword()
        }
    }
}

// MARK: - Preview

#Preview {
    AuthContainerView()
}
