

import 'package:flutter/material.dart';

class HourPickerDialog extends StatefulWidget {
  final TimeOfDay initialTime;
  HourPickerDialog({required this.initialTime});

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

class _HourPickerDialogState extends State<HourPickerDialog> {
  late int _selectedHour;
  bool _isPm = false;

  @override
  void initState() {
    super.initState();
    _selectedHour = widget.initialTime.hour > 12 ? widget.initialTime.hour - 12 : widget.initialTime.hour;
    _isPm = widget.initialTime.period == DayPeriod.pm;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('Select Hour'),
      content: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          DropdownButton<int>(
            value: _selectedHour,
            items: List.generate(12, (index) {
              int displayHour = index + 1;
              return DropdownMenuItem(
                value: displayHour,
                child: Text(displayHour.toString()),
              );
            }),
            onChanged: (value) {
              setState(() {
                _selectedHour = value!;
              });
            },
          ),
          SizedBox(width: 16.0),
          DropdownButton<bool>(
            value: _isPm,
            items: [
              DropdownMenuItem(
                value: false,
                child: Text('AM'),
              ),
              DropdownMenuItem(
                value: true,
                child: Text('PM'),
              ),
            ],
            onChanged: (value) {
              setState(() {
                _isPm = value!;
              });
            },
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(null),
          child: Text('Cancel'),
        ),
        TextButton(
          onPressed: () {
            int hour = _isPm ? _selectedHour + 12 : _selectedHour;
            Navigator.of(context).pop(TimeOfDay(hour: hour, minute: 0));
          },
          child: Text('OK'),
        ),
      ],
    );
  }
}

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