import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

import '../../../common/theme/theme.dart';
import '../spaces/space.dart';

class DateRangePickerModal {
  static Future<DateRangePickerSelectionChangedArgs?> show({
    required BuildContext context,
    String title = 'Pilih Rentang Tanggal',
    DateTime? initialStartDate,
    DateTime? initialEndDate,
    DateTime? minDate,
    DateTime? maxDate,
    String confirmText = 'Pilih',
    String cancelText = 'Batal',
    Color primaryColor = AppColor.primary,
    Function(DateTime? startDate, DateTime? endDate)? onChanged,
  }) async {
    return await showDialog<DateRangePickerSelectionChangedArgs?>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => _DateRangePickerDialog(
        title: title,
        initialStartDate: initialStartDate,
        initialEndDate: initialEndDate,
        minDate: minDate,
        maxDate: maxDate,
        confirmText: confirmText,
        cancelText: cancelText,
        primaryColor: primaryColor,
        onChanged: onChanged,
      ),
    );
  }
}

class _DateRangePickerDialog extends StatefulWidget {
  final String title;
  final DateTime? initialStartDate;
  final DateTime? initialEndDate;
  final DateTime? minDate;
  final DateTime? maxDate;
  final String confirmText;
  final String cancelText;
  final Color primaryColor;
  final Function(DateTime? startDate, DateTime? endDate)? onChanged;

  const _DateRangePickerDialog({
    required this.title,
    this.initialStartDate,
    this.initialEndDate,
    this.minDate,
    this.maxDate,
    required this.confirmText,
    required this.cancelText,
    required this.primaryColor,
    this.onChanged,
  });

  @override
  State<_DateRangePickerDialog> createState() => _DateRangePickerDialogState();
}

class _DateRangePickerDialogState extends State<_DateRangePickerDialog>
    with TickerProviderStateMixin {
  DateRangePickerSelectionChangedArgs? _selectionChangedArgs;
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.elasticOut),
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
    setState(() {
      _selectionChangedArgs = args;
    });

    // Note: onChanged callback is now called only when confirm button is pressed
    // This allows users to see real-time selection without triggering callbacks
  }

  String _getSelectionText() {
    if (_selectionChangedArgs?.value is PickerDateRange) {
      final PickerDateRange range = _selectionChangedArgs!.value;
      if (range.startDate != null && range.endDate != null) {
        return '${_formatDate(range.startDate!)} - ${_formatDate(range.endDate!)}';
      } else if (range.startDate != null) {
        return _formatDate(range.startDate!);
      }
    }
    return 'Belum ada tanggal dipilih';
  }

  String _formatDate(DateTime date) {
    final months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'Mei',
      'Jun',
      'Jul',
      'Agu',
      'Sep',
      'Okt',
      'Nov',
      'Des',
    ];
    return '${date.day} ${months[date.month - 1]} ${date.year}';
  }

  bool get _isValidSelection {
    if (_selectionChangedArgs?.value is PickerDateRange) {
      final PickerDateRange range = _selectionChangedArgs!.value;
      return range.startDate != null && range.endDate != null;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _fadeAnimation,
          child: ScaleTransition(
            scale: _scaleAnimation,
            child: Dialog(
              backgroundColor: Colors.transparent,
              elevation: 0,
              insetPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 24,
              ),
              child: Container(
                width: MediaQuery.of(context).size.width,
                constraints: BoxConstraints(
                  maxWidth: 400,
                  maxHeight: MediaQuery.of(context).size.height * 0.85,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 20,
                      offset: const Offset(0, 10),
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // Header
                    Container(
                      padding: const EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            widget.primaryColor,
                            widget.primaryColor.withOpacity(0.8),
                          ],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(20),
                          topRight: Radius.circular(20),
                        ),
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.calendar_today_rounded,
                            color: Colors.white,
                            size: 24,
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              widget.title,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    // Scrollable Content
                    Flexible(
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            SpaceHeight(16),
                            // Date Picker
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 16,
                              ),
                              child: Container(
                                height: 320,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(
                                    color: Colors.grey.withOpacity(0.2),
                                  ),
                                ),
                                child: SfDateRangePicker(
                                  onSelectionChanged: _onSelectionChanged,
                                  selectionMode:
                                      DateRangePickerSelectionMode.range,
                                  initialSelectedRange:
                                      (widget.initialStartDate != null &&
                                          widget.initialEndDate != null)
                                      ? PickerDateRange(
                                          widget.initialStartDate,
                                          widget.initialEndDate,
                                        )
                                      : null,
                                  minDate: widget.minDate,
                                  maxDate: widget.maxDate,
                                  startRangeSelectionColor: widget.primaryColor,
                                  endRangeSelectionColor: widget.primaryColor,
                                  rangeSelectionColor: widget.primaryColor
                                      .withOpacity(0.2),
                                  todayHighlightColor: widget.primaryColor,
                                  headerStyle: DateRangePickerHeaderStyle(
                                    backgroundColor: Colors.transparent,
                                    textAlign: TextAlign.center,
                                    textStyle: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  monthViewSettings:
                                      DateRangePickerMonthViewSettings(
                                        viewHeaderStyle:
                                            DateRangePickerViewHeaderStyle(
                                              backgroundColor: Colors.grey
                                                  .withOpacity(0.1),
                                              textStyle: TextStyle(
                                                fontSize: 12,
                                                fontWeight: FontWeight.w600,
                                                color: widget.primaryColor,
                                              ),
                                            ),
                                      ),
                                  selectionTextStyle: const TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 14,
                                  ),
                                  rangeTextStyle: TextStyle(
                                    color: widget.primaryColor,
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                            ),
                            // Selection Info
                            Container(
                              width: double.infinity,
                              padding: const EdgeInsets.all(12),
                              margin: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: widget.primaryColor.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: widget.primaryColor.withOpacity(0.2),
                                ),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'Tanggal Terpilih:',
                                    style: TextStyle(
                                      fontSize: 12,
                                      fontWeight: FontWeight.w500,
                                      color: widget.primaryColor,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    _getSelectionText(),
                                    style: const TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black87,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                    // Action Buttons
                    Padding(
                      padding: const EdgeInsets.all(20),
                      child: Row(
                        children: [
                          Expanded(
                            child: OutlinedButton(
                              onPressed: () => Navigator.of(context).pop(),
                              style: OutlinedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(
                                  vertical: 14,
                                ),
                                side: BorderSide(color: Colors.grey.shade400),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                              ),
                              child: Text(
                                widget.cancelText,
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.grey,
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: ElevatedButton(
                              onPressed: _isValidSelection
                                  ? () {
                                      // Call onChanged when confirm button is pressed
                                      if (widget.onChanged != null &&
                                          _selectionChangedArgs?.value
                                              is PickerDateRange) {
                                        final PickerDateRange range =
                                            _selectionChangedArgs!.value;
                                        widget.onChanged!(
                                          range.startDate,
                                          range.endDate,
                                        );
                                      }
                                      Navigator.of(
                                        context,
                                      ).pop(_selectionChangedArgs);
                                    }
                                  : null,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: widget.primaryColor,
                                padding: const EdgeInsets.symmetric(
                                  vertical: 14,
                                ),
                                elevation: 2,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                disabledBackgroundColor: Colors.grey.shade300,
                              ),
                              child: Text(
                                widget.confirmText,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: _isValidSelection
                                      ? Colors.white
                                      : Colors.grey.shade600,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
