import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

/// A date picker field for the one-time order form.
/// Matches the prototype input field style.
class OneTimeOrderDatePicker extends StatefulWidget {
  /// Creates a [OneTimeOrderDatePicker].
  const OneTimeOrderDatePicker({
    required this.label,
    required this.value,
    required this.onChanged,
    super.key,
  });

  /// The label text to display above the field.
  final String label;

  /// The currently selected date.
  final DateTime value;

  /// Callback when a new date is selected.
  final ValueChanged<DateTime> onChanged;

  @override
  State<OneTimeOrderDatePicker> createState() => _OneTimeOrderDatePickerState();
}

class _OneTimeOrderDatePickerState extends State<OneTimeOrderDatePicker> {
  late final TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(
      text: DateFormat('yyyy-MM-dd').format(widget.value),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(OneTimeOrderDatePicker oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.value != oldWidget.value) {
      _controller.text = DateFormat('yyyy-MM-dd').format(widget.value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return UiTextField(
      label: widget.label,
      controller: _controller,
      readOnly: true,
      prefixIcon: UiIcons.calendar,
      onTap: () async {
        final DateTime? picked = await showDatePicker(
          context: context,
          initialDate: widget.value,
          firstDate: DateTime.now(),
          lastDate: DateTime.now().add(const Duration(days: 365)),
        );
        if (picked != null) {
          widget.onChanged(picked);
        }
      },
    );
  }
}
