import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

// 범위 제한 Formatter (월: 1~12)
class DateRangeInputFormatter extends TextInputFormatter {
  final int min;
  final int max;

  DateRangeInputFormatter({required this.min, required this.max});

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text.isEmpty) {
      return newValue;
    }

    final int? value = int.tryParse(newValue.text);

    if (value == null) {
      return oldValue;
    }

    if (value < min || value > max) {
      if (newValue.text.length > max.toString().length) {
        return oldValue;
      }
      if (value > max) return oldValue;
    }

    return newValue;
  }
}

// 일(Day) 입력 Formatter (월에 따라 28~31일 제한)
class DayInputFormatter extends TextInputFormatter {
  final TextEditingController yearController;
  final TextEditingController monthController;

  DayInputFormatter({
    required this.yearController,
    required this.monthController,
  });

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text.isEmpty) {
      return newValue;
    }

    final int? day = int.tryParse(newValue.text);
    if (day == null) {
      return oldValue;
    }

    int year = int.tryParse(yearController.text) ?? DateTime.now().year;
    int month = int.tryParse(monthController.text) ?? 1;

    int maxDay = DateTime(year, month + 1, 0).day; // 해당 월의 마지막 날짜 계산

    if (day < 1 || day > maxDay) {
      if (newValue.text.length > maxDay.toString().length) {
        return oldValue;
      }
      if (day > maxDay) return oldValue;
    }

    return newValue;
  }
}
