/// Address Form Page
///
/// Create or edit a delivery address with full contact and location info.
/// Features:
/// - Contact information (name, phone, email, tax ID)
/// - Address selection (province/district with cascading dropdowns)
/// - Address detail text area
/// - Default address checkbox
/// - Form validation
library;

import 'package:flutter/material.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/account/domain/entities/address.dart';
import 'package:worker/features/account/domain/entities/ward.dart';
import 'package:worker/features/account/presentation/providers/address_provider.dart';
import 'package:worker/features/account/presentation/providers/location_provider.dart';

/// Address Form Page
///
/// Form for creating or editing a delivery address.
class AddressFormPage extends HookConsumerWidget {
  const AddressFormPage({super.key, this.address});

  /// Existing address for editing (null if creating new)
  final Address? address;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;

    // Form key for validation
    final formKey = useMemoized(() => GlobalKey<FormState>());

    // Form fields
    final nameController = useTextEditingController(
      text: address?.addressTitle ?? '',
    );
    final phoneController = useTextEditingController(
      text: address?.phone ?? '',
    );
    final emailController = useTextEditingController(
      text: address?.email ?? '',
    );
    final taxIdController = useTextEditingController(
      text: address?.taxCode ?? '',
    );
    final addressDetailController = useTextEditingController(
      text: address?.addressLine1 ?? '',
    );

    // Dropdown selections - use codes from Address entity
    final selectedCityCode = useState<String?>(address?.cityCode);
    final selectedWardCode = useState<String?>(address?.wardCode);

    // Default checkbox
    final isDefault = useState<bool>(address?.isDefault ?? false);

    // Loading state
    final isSaving = useState<bool>(false);

    // Get cities from API (offline-first)
    final citiesAsync = ref.watch(citiesProvider);

    // Get wards for selected city from API (offline-first)
    final AsyncValue<List<Ward>> wardsAsync = selectedCityCode.value != null
        ? ref.watch(wardsProvider(selectedCityCode.value!))
        : const AsyncValue<List<Ward>>.data([]);

    // Build cities map for dropdown
    final Map<String, String> citiesMap = citiesAsync.when(
      data: (cities) => <String, String>{
        for (final city in cities) city.code: city.cityName,
      },
      loading: () => <String, String>{},
      error: (_, __) => <String, String>{},
    );

    // Build wards map for dropdown
    final Map<String, String> wardsMap = wardsAsync.when(
      data: (wards) => <String, String>{
        for (final ward in wards) ward.code: ward.wardName,
      },
      loading: () => <String, String>{},
      error: (_, __) => <String, String>{},
    );

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: AppBarSpecs.elevation,
        leading: IconButton(
          icon: FaIcon(
            FontAwesomeIcons.arrowLeft,
            color: colorScheme.onSurface,
            size: 20,
          ),
          onPressed: () => context.pop(),
        ),
        title: Text(
          address == null ? 'Thêm địa chỉ mới' : 'Chỉnh sửa địa chỉ',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          IconButton(
            icon: FaIcon(
              FontAwesomeIcons.circleInfo,
              color: colorScheme.onSurface,
              size: 20,
            ),
            onPressed: () => _showInfoDialog(context, colorScheme),
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: Stack(
        children: [
          // Form Content
          SingleChildScrollView(
            padding: const EdgeInsets.fromLTRB(
              AppSpacing.md,
              AppSpacing.md,
              AppSpacing.md,
              100, // Space for sticky button
            ),
            child: Form(
              key: formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Contact Information Section
                  _buildSection(
                    colorScheme: colorScheme,
                    icon: FontAwesomeIcons.user,
                    title: 'Thông tin liên hệ',
                    children: [
                      _buildTextField(
                        colorScheme: colorScheme,
                        controller: nameController,
                        label: 'Họ và tên',
                        icon: FontAwesomeIcons.user,
                        placeholder: 'Nhập họ và tên người nhận',
                        isRequired: true,
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return 'Vui lòng nhập họ và tên';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: AppSpacing.md),
                      _buildTextField(
                        colorScheme: colorScheme,
                        controller: phoneController,
                        label: 'Số điện thoại',
                        icon: FontAwesomeIcons.phone,
                        placeholder: 'Nhập số điện thoại',
                        keyboardType: TextInputType.phone,
                        isRequired: true,
                        helperText: 'Định dạng: 10-11 số',
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return 'Vui lòng nhập số điện thoại';
                          }
                          if (!RegExp(r'^[0-9]{10,11}$').hasMatch(value)) {
                            return 'Số điện thoại phải có 10-11 số';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: AppSpacing.md),
                      _buildTextField(
                        colorScheme: colorScheme,
                        controller: emailController,
                        label: 'Email',
                        icon: FontAwesomeIcons.envelope,
                        placeholder: 'Nhập email',
                        keyboardType: TextInputType.emailAddress,
                        validator: (value) {
                          if (value != null &&
                              value.isNotEmpty &&
                              !RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
                                  .hasMatch(value)) {
                            return 'Email không hợp lệ';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: AppSpacing.md),
                      _buildTextField(
                        colorScheme: colorScheme,
                        controller: taxIdController,
                        label: 'Mã số thuế',
                        icon: FontAwesomeIcons.fileInvoice,
                        placeholder: 'Nhập mã số thuế',
                        keyboardType: TextInputType.number,
                      ),
                    ],
                  ),

                  const SizedBox(height: AppSpacing.md),

                  // Address Information Section
                  _buildSection(
                    colorScheme: colorScheme,
                    icon: FontAwesomeIcons.locationDot,
                    title: 'Địa chỉ giao hàng',
                    children: [
                      _buildDropdownWithLoading(
                        colorScheme: colorScheme,
                        label: 'Tỉnh/Thành phố',
                        value: selectedCityCode.value,
                        items: citiesMap,
                        isRequired: true,
                        isLoading: citiesAsync.isLoading,
                        onChanged: (value) {
                          selectedCityCode.value = value;
                          selectedWardCode.value =
                              null; // Reset ward on city change
                        },
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Vui lòng chọn Tỉnh/Thành phố';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: AppSpacing.md),
                      _buildDropdownWithLoading(
                        colorScheme: colorScheme,
                        label: 'Quận/Huyện',
                        value: selectedWardCode.value,
                        items: wardsMap,
                        isRequired: true,
                        enabled: selectedCityCode.value != null,
                        isLoading: wardsAsync.isLoading,
                        onChanged: (value) {
                          selectedWardCode.value = value;
                        },
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Vui lòng chọn Quận/Huyện';
                          }
                          return null;
                        },
                      ),
                      // Show error if cities failed to load
                      if (citiesAsync.hasError) ...[
                        const SizedBox(height: 8),
                        _buildErrorBanner(
                          colorScheme,
                          'Không thể tải danh sách tỉnh/thành phố. Vui lòng thử lại.',
                        ),
                      ],
                      // Show error if wards failed to load
                      if (wardsAsync.hasError && selectedCityCode.value != null) ...[
                        const SizedBox(height: 8),
                        _buildErrorBanner(
                          colorScheme,
                          'Không thể tải danh sách quận/huyện. Vui lòng thử lại.',
                        ),
                      ],
                      const SizedBox(height: AppSpacing.md),
                      _buildTextArea(
                        colorScheme: colorScheme,
                        controller: addressDetailController,
                        label: 'Địa chỉ cụ thể',
                        placeholder: 'Số nhà, tên đường, khu vực...',
                        isRequired: true,
                        helperText: 'Ví dụ: 123 Nguyễn Huệ, Khu phố 5',
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return 'Vui lòng nhập địa chỉ cụ thể';
                          }
                          return null;
                        },
                      ),
                    ],
                  ),

                  const SizedBox(height: AppSpacing.md),

                  // Default Address Option
                  Container(
                    padding: const EdgeInsets.all(AppSpacing.md),
                    decoration: BoxDecoration(
                      color: colorScheme.surface,
                      borderRadius: BorderRadius.circular(AppRadius.card),
                      boxShadow: [
                        BoxShadow(
                          color: colorScheme.shadow.withValues(alpha: 0.05),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        InkWell(
                          onTap: () => isDefault.value = !isDefault.value,
                          child: Row(
                            children: [
                              SizedBox(
                                width: 20,
                                height: 20,
                                child: Checkbox(
                                  value: isDefault.value,
                                  onChanged: (value) =>
                                      isDefault.value = value ?? false,
                                  activeColor: colorScheme.primary,
                                  materialTapTargetSize:
                                      MaterialTapTargetSize.shrinkWrap,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Text(
                                'Đặt làm địa chỉ mặc định',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                  color: colorScheme.onSurface,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 8),
                        Padding(
                          padding: const EdgeInsets.only(left: 32),
                          child: Text(
                            'Địa chỉ này sẽ được sử dụng làm mặc định khi đặt hàng',
                            style: TextStyle(
                              fontSize: 12,
                              color: colorScheme.onSurfaceVariant,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: AppSpacing.md),

                  // Info Note
                  Container(
                    padding: const EdgeInsets.all(AppSpacing.md),
                    decoration: BoxDecoration(
                      color: const Color(0xFFEFF6FF),
                      border: Border.all(
                        color: const Color(0xFFBFDBFE),
                        width: 1,
                      ),
                      borderRadius: BorderRadius.circular(AppRadius.card),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const FaIcon(
                          FontAwesomeIcons.circleInfo,
                          size: 18,
                          color: Color(0xFF2563EB),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: RichText(
                            text: const TextSpan(
                              style: TextStyle(
                                fontSize: 13,
                                color: Color(0xFF1E40AF),
                                height: 1.5,
                              ),
                              children: [
                                TextSpan(
                                  text: 'Lưu ý: ',
                                  style: TextStyle(
                                    fontWeight: FontWeight.w600,
                                    color: Color(0xFF1E3A8A),
                                  ),
                                ),
                                TextSpan(
                                  text:
                                      'Vui lòng kiểm tra kỹ thông tin địa chỉ để đảm bảo giao hàng chính xác. '
                                      'Bạn có thể chỉnh sửa hoặc xóa địa chỉ này sau khi lưu.',
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),

          // Sticky Footer with Save Button
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: AppSpacing.md,
                vertical: AppSpacing.md,
              ),
              decoration: BoxDecoration(
                color: colorScheme.surface,
                border: Border(
                  top: BorderSide(
                    color: colorScheme.outlineVariant,
                  ),
                ),
                boxShadow: [
                  BoxShadow(
                    color: colorScheme.shadow.withValues(alpha: 0.08),
                    blurRadius: 12,
                    offset: const Offset(0, -4),
                  ),
                ],
              ),
              child: SafeArea(
                top: false,
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: isSaving.value
                        ? null
                        : () => _handleSubmit(
                              context,
                              ref,
                              formKey,
                              nameController,
                              phoneController,
                              emailController,
                              taxIdController,
                              selectedCityCode,
                              selectedWardCode,
                              addressDetailController,
                              isDefault,
                              isSaving,
                            ),
                    icon: isSaving.value
                        ? CustomLoadingIndicator(
                            color: colorScheme.onPrimary,
                            size: 18,
                          )
                        : const FaIcon(FontAwesomeIcons.floppyDisk, size: 18),
                    label: Text(
                      isSaving.value ? 'Đang lưu...' : 'Lưu địa chỉ',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: colorScheme.primary,
                      foregroundColor: colorScheme.onPrimary,
                      disabledBackgroundColor: colorScheme.onSurfaceVariant,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      elevation: 0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(AppRadius.button),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build a section with icon and title
  Widget _buildSection({
    required ColorScheme colorScheme,
    required IconData icon,
    required String title,
    required List<Widget> children,
  }) {
    return Container(
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: colorScheme.shadow.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              FaIcon(
                icon,
                size: 16,
                color: colorScheme.primary,
              ),
              const SizedBox(width: 8),
              Text(
                title,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.onSurface,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppSpacing.md),
          ...children,
        ],
      ),
    );
  }

  /// Build a text field with label and icon
  Widget _buildTextField({
    required ColorScheme colorScheme,
    required TextEditingController controller,
    required String label,
    required IconData icon,
    required String placeholder,
    bool isRequired = false,
    TextInputType? keyboardType,
    String? helperText,
    String? Function(String?)? validator,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              label,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurface,
              ),
            ),
            if (isRequired)
              const Text(
                ' *',
                style: TextStyle(
                  fontSize: 14,
                  color: AppColors.danger,
                ),
              ),
          ],
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          keyboardType: keyboardType,
          validator: validator,
          decoration: InputDecoration(
            hintText: placeholder,
            hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
            prefixIcon: Padding(
              padding: const EdgeInsets.only(left: 16, right: 12),
              child: FaIcon(
                icon,
                size: 16,
                color: colorScheme.onSurfaceVariant,
              ),
            ),
            prefixIconConstraints: const BoxConstraints(
              minWidth: 0,
              minHeight: 0,
            ),
            filled: true,
            fillColor: colorScheme.surface,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(
                color: colorScheme.primary,
                width: 2,
              ),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(color: AppColors.danger),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(
                color: AppColors.danger,
                width: 2,
              ),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 14,
            ),
          ),
        ),
        if (helperText != null) ...[
          const SizedBox(height: 4),
          Text(
            helperText,
            style: TextStyle(
              fontSize: 12,
              color: colorScheme.onSurfaceVariant,
            ),
          ),
        ],
      ],
    );
  }

  /// Build a dropdown field
  Widget _buildDropdown({
    required ColorScheme colorScheme,
    required String label,
    required String? value,
    required Map<String, String> items,
    required void Function(String?) onChanged,
    bool isRequired = false,
    bool enabled = true,
    String? Function(String?)? validator,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              label,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurface,
              ),
            ),
            if (isRequired)
              const Text(
                ' *',
                style: TextStyle(
                  fontSize: 14,
                  color: AppColors.danger,
                ),
              ),
          ],
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          initialValue: items.containsKey(value) ? value : null,
          isExpanded: true,
          validator: validator,
          decoration: InputDecoration(
            filled: true,
            fillColor: enabled ? colorScheme.surface : colorScheme.surfaceContainerHighest,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            disabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(
                color: colorScheme.primary,
                width: 2,
              ),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(color: AppColors.danger),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(
                color: AppColors.danger,
                width: 2,
              ),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 14,
            ),
          ),
          hint: Text(
            '-- Chọn $label --',
            style: TextStyle(color: colorScheme.onSurfaceVariant),
          ),
          items: enabled
              ? () {
                  final itemsList = items.entries.map((entry) {
                    return DropdownMenuItem<String>(
                      value: entry.key,
                      child: Text(
                        entry.value,
                        style: TextStyle(
                          fontSize: 14,
                          color: colorScheme.onSurface,
                        ),
                      ),
                    );
                  }).toList();

                  // If value exists but not in items, add it as a placeholder
                  if (value != null && !items.containsKey(value)) {
                    itemsList.insert(
                      0,
                      DropdownMenuItem<String>(
                        value: value,
                        child: Text(
                          '$value (đã lưu)',
                          style: TextStyle(
                            fontSize: 14,
                            color: colorScheme.onSurfaceVariant,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      ),
                    );
                  }

                  return itemsList;
                }()
              : null,
          onChanged: enabled ? onChanged : null,
          icon: FaIcon(
            FontAwesomeIcons.chevronDown,
            size: 14,
            color: enabled ? colorScheme.onSurfaceVariant : colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
          ),
        ),
      ],
    );
  }

  /// Build a dropdown field with loading indicator
  Widget _buildDropdownWithLoading({
    required ColorScheme colorScheme,
    required String label,
    required String? value,
    required Map<String, String> items,
    required void Function(String?) onChanged,
    bool isRequired = false,
    bool enabled = true,
    bool isLoading = false,
    String? Function(String?)? validator,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              label,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurface,
              ),
            ),
            if (isRequired)
              const Text(
                ' *',
                style: TextStyle(
                  fontSize: 14,
                  color: AppColors.danger,
                ),
              ),
            if (isLoading) ...[
              const SizedBox(width: 8),
              CustomLoadingIndicator(
                color: colorScheme.primary,
                size: 12,
              ),
            ],
          ],
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          initialValue: items.containsKey(value) ? value : null,
          isExpanded: true,
          validator: validator,
          decoration: InputDecoration(
            filled: true,
            fillColor: enabled && !isLoading ? colorScheme.surface : colorScheme.surfaceContainerHighest,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            disabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(
                color: colorScheme.primary,
                width: 2,
              ),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(color: AppColors.danger),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(
                color: AppColors.danger,
                width: 2,
              ),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 14,
            ),
            suffixIcon: isLoading
                ? Padding(
                    padding: const EdgeInsets.only(right: 12),
                    child: CustomLoadingIndicator(
                      color: colorScheme.primary,
                      size: 20,
                    ),
                  )
                : null,
          ),
          hint: Text(
            isLoading
                ? 'Đang tải...'
                : !enabled
                    ? 'Vui lòng chọn Tỉnh/Thành phố trước'
                    : '-- Chọn $label --',
            style: TextStyle(
              color: colorScheme.onSurfaceVariant,
              fontSize: 14,
              fontStyle: !enabled || isLoading ? FontStyle.italic : FontStyle.normal,
            ),
          ),
          items: enabled && !isLoading
              ? () {
                  final itemsList = items.entries.map((entry) {
                    return DropdownMenuItem<String>(
                      value: entry.key,
                      child: Text(
                        entry.value,
                        style: TextStyle(
                          fontSize: 14,
                          color: colorScheme.onSurface,
                        ),
                      ),
                    );
                  }).toList();

                  // If value exists but not in items, add it as a placeholder
                  if (value != null && !items.containsKey(value)) {
                    itemsList.insert(
                      0,
                      DropdownMenuItem<String>(
                        value: value,
                        child: Text(
                          '$value (đã lưu)',
                          style: TextStyle(
                            fontSize: 14,
                            color: colorScheme.onSurfaceVariant,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      ),
                    );
                  }

                  return itemsList;
                }()
              : null,
          onChanged: enabled && !isLoading ? onChanged : null,
          icon: FaIcon(
            FontAwesomeIcons.chevronDown,
            size: 14,
            color: enabled && !isLoading
                ? colorScheme.onSurfaceVariant
                : colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
          ),
        ),
      ],
    );
  }

  /// Build a text area field
  Widget _buildTextArea({
    required ColorScheme colorScheme,
    required TextEditingController controller,
    required String label,
    required String placeholder,
    bool isRequired = false,
    String? helperText,
    String? Function(String?)? validator,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              label,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurface,
              ),
            ),
            if (isRequired)
              const Text(
                ' *',
                style: TextStyle(
                  fontSize: 14,
                  color: AppColors.danger,
                ),
              ),
          ],
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          maxLines: 3,
          validator: validator,
          decoration: InputDecoration(
            hintText: placeholder,
            hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
            filled: true,
            fillColor: colorScheme.surface,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(
                color: colorScheme.primary,
                width: 2,
              ),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(color: AppColors.danger),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(
                color: AppColors.danger,
                width: 2,
              ),
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
        if (helperText != null) ...[
          const SizedBox(height: 4),
          Text(
            helperText,
            style: TextStyle(
              fontSize: 12,
              color: colorScheme.onSurfaceVariant,
            ),
          ),
        ],
      ],
    );
  }

  /// Build error banner for API failures
  Widget _buildErrorBanner(ColorScheme colorScheme, String message) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: const Color(0xFFFEF2F2),
        border: Border.all(
          color: const Color(0xFFFECACA),
          width: 1,
        ),
        borderRadius: BorderRadius.circular(AppRadius.card),
      ),
      child: Row(
        children: [
          const FaIcon(
            FontAwesomeIcons.circleExclamation,
            size: 16,
            color: Color(0xFFDC2626),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF991B1B),
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Show info dialog
  void _showInfoDialog(BuildContext context, ColorScheme colorScheme) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text(
          'Hướng dẫn điền địa chỉ',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        content: const SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('Vui lòng điền đầy đủ thông tin:'),
              SizedBox(height: 12),
              Text('• Họ và tên người nhận hàng'),
              Text('• Số điện thoại liên hệ (10-11 số)'),
              Text('• Email (không bắt buộc)'),
              Text('• Mã số thuế (nếu có)'),
              Text('• Tỉnh/Thành phố và Quận/Huyện'),
              Text('• Địa chỉ chi tiết (số nhà, đường, khu vực)'),
              SizedBox(height: 12),
              Text(
                'Địa chỉ được đánh dấu "mặc định" sẽ tự động '
                'được chọn khi đặt hàng.',
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Đóng'),
          ),
        ],
      ),
    );
  }

  /// Handle form submission
  Future<void> _handleSubmit(
    BuildContext context,
    WidgetRef ref,
    GlobalKey<FormState> formKey,
    TextEditingController nameController,
    TextEditingController phoneController,
    TextEditingController emailController,
    TextEditingController taxIdController,
    ValueNotifier<String?> selectedCityCode,
    ValueNotifier<String?> selectedWardCode,
    TextEditingController addressDetailController,
    ValueNotifier<bool> isDefault,
    ValueNotifier<bool> isSaving,
  ) async {
    // Validate form
    if (!formKey.currentState!.validate()) {
      return;
    }

    // Set loading state
    isSaving.value = true;

    try {
      // Build Address entity
      final newAddress = Address(
        name: address?.name ?? '', // Empty for creation, existing for update
        addressTitle: nameController.text.trim(),
        addressLine1: addressDetailController.text.trim(),
        phone: phoneController.text.trim(),
        email: emailController.text.trim().isEmpty ? null : emailController.text.trim(),
        taxCode: taxIdController.text.trim().isEmpty ? null : taxIdController.text.trim(),
        cityCode: selectedCityCode.value!,
        wardCode: selectedWardCode.value!,
        isDefault: isDefault.value,
      );

      // Call API to create or update
      if (address == null) {
        // Creating new address
        await ref.read(addressesProvider.notifier).createAddress(newAddress);
      } else {
        // Updating existing address
        await ref.read(addressesProvider.notifier).updateAddress(newAddress);
      }

      // Reset loading state
      isSaving.value = false;

      // Show success message
      if (!context.mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const FaIcon(FontAwesomeIcons.circleCheck, color: Colors.white, size: 18),
              const SizedBox(width: 12),
              Text(address == null ? 'Đã thêm địa chỉ thành công!' : 'Đã cập nhật địa chỉ thành công!'),
            ],
          ),
          backgroundColor: AppColors.success,
          duration: const Duration(seconds: 2),
        ),
      );

      // Navigate back after short delay
      if (context.mounted) {
        Future.delayed(const Duration(milliseconds: 500), () {
          if (context.mounted) {
            context.pop();
          }
        });
      }
    } catch (e) {
      // Reset loading state
      isSaving.value = false;

      // Show error message
      if (!context.mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const FaIcon(FontAwesomeIcons.circleExclamation, color: Colors.white, size: 18),
              const SizedBox(width: 12),
              Expanded(child: Text('Lỗi: ${e.toString()}')),
            ],
          ),
          backgroundColor: AppColors.danger,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }
}
