import 'package:flutter/material.dart';
import 'package:test_sa/views/app_style/sizing.dart';

class ADateTimePicker extends StatelessWidget {
  final DateTime date;
  final DateTime from;
  final DateTime to;
  final Function(DateTime) onDateTimePicker;

  const ADateTimePicker({Key key, this.date, this.onDateTimePicker, this.from, this.to}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        foregroundColor: Colors.white,
        textStyle: Theme.of(context).textTheme.subtitle2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12 * AppStyle.getScaleFactor(context)),
        ),
      ),
      child: Text(
        date == null ? "Pick Time" : date.toString().substring(0, date.toString().lastIndexOf(":")),
        textScaleFactor: AppStyle.getScaleFactor(context),
      ),
      onPressed: () async {
        //    TimeOfDay picked = await showTimePicker(context: context, initialTime: TimeOfDay.now());
        onDateTimePicker(await showDateTimePicker(context: context, initialDate: date, firstDate: from, lastDate: to));
      },
    );
  }
}

Future<DateTime> showDateTimePicker({
  BuildContext context,
  DateTime initialDate,
  DateTime firstDate,
  DateTime lastDate,
}) async {
  initialDate ??= DateTime.now();
  firstDate ??= initialDate.subtract(const Duration(days: 365 * 100));
  lastDate ??= firstDate.add(const Duration(days: 365 * 200));

  final DateTime selectedDate = await showDatePicker(
    context: context,
    initialDate: initialDate,
    firstDate: firstDate,
    lastDate: lastDate,
  );

  if (selectedDate == null) return null;

  if (!context.mounted) return selectedDate;

  final TimeOfDay selectedTime = await showTimePicker(
    context: context,
    initialTime: TimeOfDay.fromDateTime(selectedDate),
  );

  return selectedTime == null
      ? selectedDate
      : DateTime(
          selectedDate.year,
          selectedDate.month,
          selectedDate.day,
          selectedTime.hour,
          selectedTime.minute,
        );
}
