//
//  LoginView.swift
//  AppClientBaseSwift
//
//  Login screen view - Pastel Yellow Theme
//  View màn hình đăng nhập - Theme Pastel Vàng
//

import SwiftUI
import Combine

// MARK: - Login View
// View Đăng nhập

/// Login screen with email/password authentication
/// Màn hình đăng nhập với xác thực email/password
struct LoginView: View {

    // MARK: - Properties

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

    /// Focus state for text fields
    /// State focus cho các text field
    @FocusState private var focusedField: Field?

    enum Field {
        case email
        case password
    }

    // MARK: - Body

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

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

                // Login button
                loginButton
                    .padding(.horizontal, DesignSystem.spacingLG)

                // Divider with text
                dividerSection
                    .padding(.horizontal, DesignSystem.spacingLG)

                // Social login buttons
                socialButtons
                    .padding(.horizontal, DesignSystem.spacingLG)

                // Register link
                registerSection
                    .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 ?? "")
        }
    }

    // MARK: - Subviews

    /// Header with logo and title
    /// Header với logo và tiêu đề
    private var headerSection: some View {
        VStack(spacing: DesignSystem.spacingMD) {
            // Logo
            ZStack {
                Circle()
                    .fill(AppTheme.primaryGradient)
                    .frame(width: 80, height: 80)

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

            // Title
            VStack(spacing: DesignSystem.spacingXS) {
                Text("Chào mừng trở lại!")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundStyle(Color.textPrimary)

                Text("Đăng nhập để tiếp tục")
                    .font(.subheadline)
                    .foregroundStyle(Color.textSecondary)
            }
        }
    }

    /// Form with email and password fields
    /// Form với các field email và password
    private var formSection: some View {
        VStack(spacing: DesignSystem.spacingMD) {
            // Email field
            AuthTextField(
                icon: "envelope.fill",
                placeholder: "Email",
                text: $viewModel.loginEmail,
                keyboardType: .emailAddress
            )
            .focused($focusedField, equals: .email)
            .submitLabel(.next)
            .onSubmit { focusedField = .password }

            // Password field
            AuthSecureField(
                icon: "lock.fill",
                placeholder: "Mật khẩu",
                text: $viewModel.loginPassword
            )
            .focused($focusedField, equals: .password)
            .submitLabel(.go)
            .onSubmit { login() }

            // Forgot password link
            HStack {
                Spacer()
                Button {
                    viewModel.navigateTo(.forgotPassword)
                } label: {
                    Text("Quên mật khẩu?")
                        .font(.subheadline)
                        .foregroundStyle(Color.brandAccent)
                }
            }
        }
    }

    /// Login button
    /// Nút đăng nhập
    private var loginButton: some View {
        Button(action: login) {
            HStack(spacing: DesignSystem.spacingSM) {
                Text("Đăng nhập")
                    .fontWeight(.semibold)

                Image(systemName: "arrow.right")
            }
            .font(.headline)
            .foregroundStyle(Color.textPrimary)
            .frame(maxWidth: .infinity)
            .padding(.vertical, DesignSystem.spacingMD)
            .background(
                Group {
                    if viewModel.isLoginValid {
                        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.isLoginValid ? AppTheme.buttonShadow : .clear,
                radius: 15,
                x: 0,
                y: 8
            )
        }
        .disabled(!viewModel.isLoginValid)
    }

    /// Divider with "or" text
    /// Divider với chữ "hoặc"
    private var dividerSection: some View {
        HStack(spacing: DesignSystem.spacingMD) {
            Rectangle()
                .fill(Color.textSecondary.opacity(0.3))
                .frame(height: 1)

            Text("hoặc")
                .font(.subheadline)
                .foregroundStyle(Color.textSecondary)

            Rectangle()
                .fill(Color.textSecondary.opacity(0.3))
                .frame(height: 1)
        }
    }

    /// Social login buttons
    /// Các nút đăng nhập mạng xã hội
    private var socialButtons: some View {
        HStack(spacing: DesignSystem.spacingMD) {
            SocialLoginButton(icon: "apple.logo", color: .black) {
                // Apple login
            }

            SocialLoginButton(icon: "g.circle.fill", color: Color(red: 0.9, green: 0.3, blue: 0.2)) {
                // Google login
            }

            SocialLoginButton(icon: "f.circle.fill", color: Color(red: 0.2, green: 0.4, blue: 0.8)) {
                // Facebook login
            }
        }
    }

    /// Register link section
    /// Phần link đăng ký
    private var registerSection: some View {
        HStack(spacing: DesignSystem.spacingXS) {
            Text("Chưa có tài khoản?")
                .foregroundStyle(Color.textSecondary)

            Button {
                viewModel.navigateTo(.register)
            } label: {
                Text("Đăng ký ngay")
                    .fontWeight(.semibold)
                    .foregroundStyle(Color.brandAccent)
            }
        }
        .font(.subheadline)
    }

    // MARK: - Methods

    /// Perform login
    /// Thực hiện đăng nhập
    private func login() {
        focusedField = nil
        Task {
            await viewModel.login()
        }
    }
}

// MARK: - Auth Text Field
// Text Field Auth

/// Custom text field for auth forms - Pastel Theme
/// Text field tùy chỉnh cho form auth - Theme Pastel
struct AuthTextField: View {
    let icon: String
    let placeholder: String
    @Binding var text: String
    var keyboardType: UIKeyboardType = .default

    var body: some View {
        HStack(spacing: DesignSystem.spacingMD) {
            Image(systemName: icon)
                .font(.system(size: 18))
                .foregroundStyle(Color.brandAccent)
                .frame(width: 24)

            TextField("", text: $text, prompt: Text(placeholder).foregroundStyle(Color.textSecondary.opacity(0.6)))
                .foregroundStyle(Color.textPrimary)
                .keyboardType(keyboardType)
                .textInputAutocapitalization(.never)
                .autocorrectionDisabled()
        }
        .padding(.horizontal, DesignSystem.spacingMD)
        .padding(.vertical, DesignSystem.spacingMD)
        .background(Color.cardBackground)
        .cornerRadius(DesignSystem.cornerRadiusMD)
        .overlay(
            RoundedRectangle(cornerRadius: DesignSystem.cornerRadiusMD)
                .stroke(Color.brandPrimary.opacity(0.5), lineWidth: 1.5)
        )
        .shadow(color: AppTheme.cardShadow, radius: 5, x: 0, y: 2)
    }
}

// MARK: - Auth Secure Field
// Secure Field Auth

/// Custom secure field for auth forms - Pastel Theme
/// Secure field tùy chỉnh cho form auth - Theme Pastel
struct AuthSecureField: View {
    let icon: String
    let placeholder: String
    @Binding var text: String
    @State private var isVisible = false

    var body: some View {
        HStack(spacing: DesignSystem.spacingMD) {
            Image(systemName: icon)
                .font(.system(size: 18))
                .foregroundStyle(Color.brandAccent)
                .frame(width: 24)

            Group {
                if isVisible {
                    TextField("", text: $text, prompt: Text(placeholder).foregroundStyle(Color.textSecondary.opacity(0.6)))
                } else {
                    SecureField("", text: $text, prompt: Text(placeholder).foregroundStyle(Color.textSecondary.opacity(0.6)))
                }
            }
            .foregroundStyle(Color.textPrimary)
            .textInputAutocapitalization(.never)
            .autocorrectionDisabled()

            Button {
                isVisible.toggle()
            } label: {
                Image(systemName: isVisible ? "eye.slash.fill" : "eye.fill")
                    .foregroundStyle(Color.textSecondary)
            }
        }
        .padding(.horizontal, DesignSystem.spacingMD)
        .padding(.vertical, DesignSystem.spacingMD)
        .background(Color.cardBackground)
        .cornerRadius(DesignSystem.cornerRadiusMD)
        .overlay(
            RoundedRectangle(cornerRadius: DesignSystem.cornerRadiusMD)
                .stroke(Color.brandPrimary.opacity(0.5), lineWidth: 1.5)
        )
        .shadow(color: AppTheme.cardShadow, radius: 5, x: 0, y: 2)
    }
}

// MARK: - Social Login Button
// Nút đăng nhập mạng xã hội

/// Social login button component - Pastel Theme
/// Component nút đăng nhập mạng xã hội - Theme Pastel
struct SocialLoginButton: View {
    let icon: String
    let color: Color
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Image(systemName: icon)
                .font(.system(size: 24))
                .foregroundStyle(color)
                .frame(width: 56, height: 56)
                .background(Color.cardBackground)
                .cornerRadius(DesignSystem.cornerRadiusMD)
                .overlay(
                    RoundedRectangle(cornerRadius: DesignSystem.cornerRadiusMD)
                        .stroke(Color.brandPrimary.opacity(0.3), lineWidth: 1)
                )
                .shadow(color: AppTheme.cardShadow, radius: 5, x: 0, y: 2)
        }
    }
}

// MARK: - Preview

#Preview {
    AuthContainerView()
}
