import 'package:flutter/material.dart';

class Datum extends StatefulWidget {
  final DateTime? initDatum;
  final Function(DateTime) onDateChanged;
  final String name;

  const Datum(
      {super.key, required this.initDatum, required this.onDateChanged, required this.name});

  @override
  State<Datum> createState() => _DatumState();
}

class _DatumState extends State<Datum> {
  DateTime? datum;

  @override
  void initState() {
    super.initState();
    datum = widget.initDatum;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Row(children: [
          SizedBox(
            width: 140,
            child: ElevatedButton(
                onPressed: () async {
                  final date = await pickDate();
                  if (date == null) return;
                  setState(() => datum = date);
                  widget.onDateChanged(date);
                },
                child: Text(widget.name)),
          ),
          const SizedBox(
            width: 10,
          ),
          Text(
            '${datum?.day}. ${datum?.month}. ${datum?.year}',
          ),
        ]),
      ],
    );
  }

  Future<DateTime?> pickDate() async {
    final date = await showDatePicker(
        context: context,
        initialDate: datum!,
        firstDate: DateTime(2000),
        lastDate: DateTime(5000));

    return date;
  }
}
