// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/components/rect_icon_button.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/dialog_date.dart';

class DateSelectorField extends StatefulWidget {
  DateSelectorField({
    super.key,
    this.label = "Label",
    this.hintText = "",
    this.initialValue,
    this.editable = true,
    this.onChanged,
  });

  final String label;
  final String hintText;
  DateTime? initialValue;
  final bool editable;
  final ValueChanged<DateTime>? onChanged;
  final TextEditingController controller = TextEditingController();
  final FocusNode focusNode = FocusNode();

  @override
  State<DateSelectorField> createState() => _DateSelectorFieldState();
}

class _DateSelectorFieldState extends State<DateSelectorField> {
  bool _isHover = false;
  late TextEditingController _monthController;
  late TextEditingController _dayController;
  late TextEditingController _yearController;
  @override
  void initState() {
    super.initState();
    _monthController = TextEditingController(
      text: widget.initialValue?.month.toString() ?? '',
    );
    _monthController.addListener(_updateDate);

    _dayController = TextEditingController(
      text: widget.initialValue?.day.toString() ?? '',
    );
    _dayController.addListener(_updateDate);

    _yearController = TextEditingController(
      text: widget.initialValue?.year.toString() ?? '',
    );
    _yearController.addListener(_updateDate);
  }

  void _updateDate() {
    final month = int.tryParse(_monthController.text) ?? 0;
    final day = int.tryParse(_dayController.text) ?? 0;
    final year = int.tryParse(_yearController.text) ?? 0;

    final newDate = DateTime(year, month, day);
    widget.onChanged?.call(newDate);
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: GestureDetector(
        onTap: _handleTap,
        child: MouseRegion(
          cursor: SystemMouseCursors.text,
          onEnter: _handleMouseEnter,
          onExit: _handleMouseExit,
          child: Container(
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
              color: _isHover ? LabColors.base300 : Colors.transparent,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "出生日期（月-日-年）",
                  style: TextStyle(
                    fontSize: 14,
                    color: LabColors.text600,
                  ),
                ),
                SizedBox(height: 2),
                Row(
                  children: [
                    Container(
                      width: 30,
                      child: TextField(
                        maxLength: 2,
                        decoration: null,
                        controller: _monthController,
                        style: TextStyle(
                          fontSize: 18,
                          color: LabColors.text800,
                        ),
                      ),
                    ),
                    Text("-",
                        style:
                            TextStyle(fontSize: 18, color: LabColors.text600)),
                    SizedBox(width: 10),
                    Container(
                      width: 30,
                      child: TextField(
                        maxLength: 2,
                        decoration: null,
                        controller: _dayController,
                        style: TextStyle(
                          fontSize: 18,
                          color: LabColors.text800,
                        ),
                      ),
                    ),
                    Text("-",
                        style:
                            TextStyle(fontSize: 18, color: LabColors.text600)),
                    SizedBox(width: 10),
                    Flexible(
                      child: TextField(
                        maxLength: 4,
                        decoration: null,
                        controller: _yearController,
                        style: TextStyle(
                          fontSize: 18,
                          color: LabColors.text800,
                        ),
                      ),
                    ),
                    RectIconButton(
                      size: Size(25, 25),
                      icon: Icons.calendar_today,
                      iconSize: 20,
                      iconColor: LabColors.base800,
                      tooltipMessage: "选择日期",
                      onPressed: _changeBirthDay,
                    )
                  ],
                ),
                Container(
                  height: 2,
                  color: LabColors.base600,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _changeBirthDay() async {
    var result = await VDialogDate(
      title: "选择日期",
      // minimumDate: appointment?.appointmentStartTime,
      initialValue: widget.initialValue,
      // maxValue: latestTime,
    ).show();
    widget.initialValue = result;
    if (result is DateTime) {
      _monthController.text = result.month.toString();
      _yearController.text = result.year.toString();
      _dayController.text = result.day.toString();
    }
    widget.onChanged?.call(result);
    setState(() {});
  }

  void _handleMouseEnter(PointerEvent details) {
    setState(() {
      _isHover = true;
    });
  }

  void _handleMouseExit(PointerEvent details) {
    setState(() {
      _isHover = false;
    });
  }

  // 如果没聚焦，点击后聚焦
  void _handleTap() {
    if (!widget.focusNode.hasFocus) {
      widget.focusNode.requestFocus();
    }
  }
}
