/// Delivery Information Section Widget
///
/// Shows delivery address selection and pickup date/notes.
library;

import 'package:flutter/material.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/presentation/providers/address_provider.dart';
import 'package:worker/features/cart/presentation/widgets/checkout_date_picker_field.dart';
import 'package:worker/features/cart/presentation/widgets/checkout_text_field.dart';

/// Delivery Information Section
///
/// Shows default address selection and delivery details.
/// Matches HTML design from checkout.html.
class DeliveryInformationSection extends HookConsumerWidget {
  const DeliveryInformationSection({
    super.key,
    required this.notesController,
    required this.selectedPickupDate,
    required this.selectedAddress,
  });

  final TextEditingController notesController;
  final ValueNotifier<DateTime?> selectedPickupDate;
  final ValueNotifier<Address?> selectedAddress;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Watch the default address
    final defaultAddr = ref.watch(defaultAddressProvider);

    // Initialize selected address with default address when it loads
    // Only update if user hasn't manually selected a different address
    useEffect(() {
      if (defaultAddr != null && selectedAddress.value == null) {
        // Use Future.microtask to avoid setState during build
        Future.microtask(() {
          if (selectedAddress.value == null) {
            selectedAddress.value = defaultAddr;
          }
        });
      }
      return null;
    }, [defaultAddr]); // Watch defaultAddr changes

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Section Title
          Row(
            children: [
              const FaIcon(
                FontAwesomeIcons.truck,
                color: AppColors.primaryBlue,
                size: 16,
              ),
              const SizedBox(width: AppSpacing.sm),
              const Text(
                'Thông tin giao hàng',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF212121),
                ),
              ),
            ],
          ),

          const SizedBox(height: AppSpacing.md),

          // Address Selection
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Địa chỉ nhận hàng',
                style: TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                  color: Color(0xFF424242),
                ),
              ),
              const SizedBox(height: AppSpacing.sm),

              // Address Card
              if (selectedAddress.value != null)
                InkWell(
                  onTap: () async {
                    // Navigate to address selection and wait for result
                    final result = await context.push<Address>(
                      '/account/addresses',
                      extra: {
                        'selectMode': true,
                        'currentAddress': selectedAddress.value,
                      },
                    );

                    // Update selected address if user picked one
                    if (result != null) {
                      selectedAddress.value = result;
                    }
                  },
                  borderRadius: BorderRadius.circular(AppRadius.sm),
                  child: Container(
                    padding: const EdgeInsets.all(AppSpacing.sm),
                    decoration: BoxDecoration(
                      border: Border.all(color: const Color(0xFFE0E0E0)),
                      borderRadius: BorderRadius.circular(AppRadius.sm),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // Name
                              Text(
                                selectedAddress.value!.addressTitle,
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: Color(0xFF212121),
                                ),
                              ),
                              const SizedBox(height: 4),

                              // Phone
                              Text(
                                selectedAddress.value!.phone,
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Color(0xFF757575),
                                ),
                              ),
                              const SizedBox(height: 2),

                              // Address
                              Text(
                                selectedAddress.value!.fullAddress,
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Color(0xFF757575),
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: AppSpacing.sm),
                        const FaIcon(
                          FontAwesomeIcons.chevronRight,
                          size: 14,
                          color: Color(0xFF9E9E9E),
                        ),
                      ],
                    ),
                  ),
                )
              else
                // No address selected - show add button
                InkWell(
                  onTap: () async {
                    final result = await context.push<Address>(
                      '/account/addresses',
                      extra: {'selectMode': true, 'currentAddress': null},
                    );

                    if (result != null) {
                      selectedAddress.value = result;
                    }
                  },
                  borderRadius: BorderRadius.circular(AppRadius.sm),
                  child: Container(
                    padding: const EdgeInsets.all(AppSpacing.md),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: AppColors.primaryBlue,
                        style: BorderStyle.solid,
                      ),
                      borderRadius: BorderRadius.circular(AppRadius.sm),
                    ),
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        FaIcon(
                          FontAwesomeIcons.plus,
                          size: 14,
                          color: AppColors.primaryBlue,
                        ),
                        SizedBox(width: AppSpacing.sm),
                        Text(
                          'Thêm địa chỉ giao hàng',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: AppColors.primaryBlue,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),

          const SizedBox(height: AppSpacing.md),

          // Pickup Date
          CheckoutDatePickerField(
            label: 'Ngày lấy hàng',
            selectedDate: selectedPickupDate,
          ),

          const SizedBox(height: AppSpacing.md),

          // Notes
          CheckoutTextField(
            label: 'Ghi chú',
            controller: notesController,
            required: false,
            maxLines: 2,
            hintText: 'Ví dụ: Thời gian yêu cầu giao hàng, lưu ý đặc biệt...',
          ),
        ],
      ),
    );
  }
}
