import 'package:flutter/material.dart';

import '../../../shared/widgets/inputs/modern_text_field.dart';
import 'base_field.dart';

/// Date input field implementation with native date picker
class DateField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final DateTime? initialDate;
  final DateTime firstDate;
  final DateTime lastDate;

  DateField({
    required this.fieldKey,
    required this.label,
    required this.hint,
    this.isRequired = false,
    this.initialDate,
    DateTime? firstDate,
    DateTime? lastDate,
  })  : firstDate = firstDate ?? DateTime(2000),
        lastDate = lastDate ?? DateTime(2101);

  @override
  String? Function(String?)? get validator => (value) {
        if (isRequired && (value == null || value.isEmpty)) {
          return '$label is required';
        }
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return Builder(
      builder: (context) {
        return ModernTextField(
          controller: controller,
          hint: hint.isNotEmpty ? hint : label,
          readOnly: true,
          validator: validator,
          suffixIcon: const Icon(Icons.calendar_today_rounded),
          onTap: () async {
            FocusScope.of(context).unfocus();
            final now = DateTime.now();
            final picked = await showDatePicker(
              context: context,
              initialDate: initialDate ?? now,
              firstDate: firstDate,
              lastDate: lastDate,
              helpText: label,
            );
            if (picked != null) {
              final String value = _formatDate(picked);
              controller.text = value;
              if (onChanged != null) onChanged();
            }
          },
        );
      },
    );
  }

  String _formatDate(DateTime date) {
    String two(int n) => n < 10 ? '0$n' : '$n';
    return '${date.year}-${two(date.month)}-${two(date.day)}';
  }
}

// No global navigator key required; Builder provides local context
