import 'package:flutter/material.dart';
import 'base_field.dart';
import 'package:flutter/material.dart';
import 'base_field.dart';
import '../../../shared/widgets/inputs/modern_text_field.dart';

/// DateTime input field implementation with native date & time pickers
class DateTimeField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final DateTime? initialDateTime;
  final DateTime firstDate;
  final DateTime lastDate;

  DateTimeField({
    required this.fieldKey,
    required this.label,
    required this.hint,
    this.isRequired = false,
    this.initialDateTime,
    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.access_time_rounded),
          onTap: () async {
            FocusScope.of(context).unfocus();
            final now = DateTime.now();
            final datePicked = await showDatePicker(
              context: context,
              initialDate: (initialDateTime ?? now),
              firstDate: firstDate,
              lastDate: lastDate,
              helpText: label,
            );
            if (datePicked == null) return;
            final timePicked = await showTimePicker(
              context: context,
              initialTime: TimeOfDay.fromDateTime(initialDateTime ?? now),
              helpText: label,
            );
            if (timePicked == null) return;
            final combined = DateTime(
              datePicked.year,
              datePicked.month,
              datePicked.day,
              timePicked.hour,
              timePicked.minute,
            );
            controller.text = _formatDateTime(combined);
            if (onChanged != null) onChanged();
          },
        );
      },
    );
  }

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