

import 'package:flutter/material.dart';

class HourPickerDialog extends StatefulWidget {
  final TimeOfDay initialTime;

  const HourPickerDialog({super.key, required this.initialTime});

  @override
  _HourPickerDialogState createState() => _HourPickerDialogState();
}

class _HourPickerDialogState extends State<HourPickerDialog> {
  late String selectedHour;

  @override
  void initState() {
    super.initState();
    // Initialize the selectedHour with the initial time passed to the dialog
    selectedHour = widget.initialTime.hour.toString().padLeft(2, '0') + ':00';
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Select Hour'),
      content: DropdownButton<String>(
        value: selectedHour, // Show the currently selected hour
        items: List.generate(24, (index) {
          String hour = index.toString().padLeft(2, '0');
          return DropdownMenuItem<String>(
            value: '$hour:00',
            child: Text('$hour:00'),
          );
        }),
        onChanged: (String? newValue) {
          if (newValue != null) {
            setState(() {
              selectedHour = newValue; // Update the selected hour without closing the dialog
            });
          }
        },
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(null), // Close the dialog without selection
          child: const Text('Cancel'),
        ),
        TextButton(
          onPressed: () {
            // Close the dialog and return the selected time
            Navigator.of(context).pop(
              TimeOfDay(
                hour: int.parse(selectedHour.split(':')[0]),
                minute: 0,
              ),
            );
          },
          child: const Text('OK'),
        ),
      ],
    );
  }
}

Future<TimeOfDay?> showHourPicker({
  required BuildContext context,
  required TimeOfDay initialTime,
}) {
  return showDialog<TimeOfDay>(
    barrierDismissible: false,
    context: context,
    builder: (context) => HourPickerDialog(initialTime: initialTime),
  );
}
