import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

class DatePickerField extends StatelessWidget {
  final String label;
  final TextEditingController controller;
  final String? errorText;
  final Function(DateTime) onDateSelected;
  final DateTime? firstDate;
  final DateTime? lastDate;
  final String dateFormat;

  const DatePickerField({
    super.key,
    required this.label,
    required this.controller,
    this.errorText,
    required this.onDateSelected,
    this.firstDate,
    this.lastDate,
    this.dateFormat = 'yyyy-MM-dd',
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: Theme.of(context).textTheme.bodyMedium),
        const SizedBox(height: TSizes.xs),
        GestureDetector(
          onTap: () => _showDatePicker(context),
          child: Container(
            padding: const EdgeInsets.symmetric(
              horizontal: TSizes.md,
              vertical: TSizes.md,
            ),
            decoration: BoxDecoration(
              border: Border.all(
                color:
                    errorText != null && errorText!.isNotEmpty
                        ? TColors.error
                        : TColors.textSecondary,
              ),
              borderRadius: BorderRadius.circular(TSizes.borderRadiusLg),
              color: Colors.transparent,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  controller.text.isEmpty ? 'Select $label' : controller.text,
                  style: TextStyle(
                    color:
                        controller.text.isEmpty
                            ? Theme.of(context).textTheme.bodyMedium?.color
                            : TColors.textSecondary,
                  ),
                ),
                Icon(
                  Icons.calendar_today,
                  size: TSizes.iconSm,
                  color: Theme.of(context).textTheme.bodyMedium?.color,
                ),
              ],
            ),
          ),
        ),
        if (errorText != null && errorText!.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: TSizes.xs, left: TSizes.xs),
            child: Text(
              errorText!,
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                color: TColors.error,
                fontSize: 12,
              ),
            ),
          ),
        const SizedBox(height: TSizes.spaceBtwItems),
      ],
    );
  }

  void _showDatePicker(BuildContext context) async {
    final results = await showCalendarDatePicker2Dialog(
      context: context,
      config: CalendarDatePicker2WithActionButtonsConfig(
        calendarType: CalendarDatePicker2Type.single,
        selectedDayHighlightColor: TColors.primary,
        lastDate: lastDate ?? DateTime.now(),
        firstDate: firstDate ?? DateTime(1900),
      ),
      dialogSize: const Size(325, 400),
      borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
      value:
          controller.text.isNotEmpty
              ? [_parseDate(controller.text)]
              : <DateTime?>[],
    );

    if (results != null && results.isNotEmpty && results[0] != null) {
      final selectedDate = results[0]!;
      final formattedDate = DateFormat(dateFormat).format(selectedDate);
      controller.text = formattedDate;
      onDateSelected(selectedDate);
    }
  }

  DateTime? _parseDate(String dateStr) {
    try {
      return DateFormat(dateFormat).parse(dateStr);
    } catch (e) {
      return null;
    }
  }
}
