/// 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/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) {
    final colorScheme = Theme.of(context).colorScheme;

    // 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: colorScheme.surface,
        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: [
              FaIcon(
                FontAwesomeIcons.truck,
                color: colorScheme.primary,
                size: 16,
              ),
              const SizedBox(width: AppSpacing.sm),
              Text(
                'Thông tin giao hàng',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.onSurface,
                ),
              ),
            ],
          ),

          const SizedBox(height: AppSpacing.md),

          // Address Selection
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Địa chỉ nhận hàng',
                style: TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                  color: colorScheme.onSurface,
                ),
              ),
              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: colorScheme.outline),
                      borderRadius: BorderRadius.circular(AppRadius.sm),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // Name
                              Text(
                                selectedAddress.value!.addressTitle,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: colorScheme.onSurface,
                                ),
                              ),
                              const SizedBox(height: 4),

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

                              // Address
                              Text(
                                selectedAddress.value!.fullAddress,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: colorScheme.onSurfaceVariant,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: AppSpacing.sm),
                        FaIcon(
                          FontAwesomeIcons.chevronRight,
                          size: 14,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ],
                    ),
                  ),
                )
              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: colorScheme.primary,
                        style: BorderStyle.solid,
                      ),
                      borderRadius: BorderRadius.circular(AppRadius.sm),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        FaIcon(
                          FontAwesomeIcons.plus,
                          size: 14,
                          color: colorScheme.primary,
                        ),
                        const SizedBox(width: AppSpacing.sm),
                        Text(
                          'Thêm địa chỉ giao hàng',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: colorScheme.primary,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),

          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...',
          ),
        ],
      ),
    );
  }
}
