import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'dart:math' as math;

/// Date-range dialog with quick presets (Today, Yesterday, Month, Custom Range),
/// dual-month calendar, and Apply / Clear.
Future<DateTimeRange?> showCompactDateRangePicker({
  required BuildContext context,
  required DateTime firstDate,
  required DateTime lastDate,
  DateTimeRange? initialRange,
}) {
  final box = context.findRenderObject();
  final screenSize = MediaQuery.sizeOf(context);
  const margin = 12.0;
  const gap = 6.0;

  var left = margin;
  var top = margin;
  var popupWidth = math.min(720.0, screenSize.width - (margin * 2));

  if (box is RenderBox) {
    final offset = box.localToGlobal(Offset.zero);
    final fieldSize = box.size;
    popupWidth = math.min(720.0, screenSize.width - (margin * 2));
    left = offset.dx.clamp(margin, screenSize.width - popupWidth - margin);
    top = (offset.dy + fieldSize.height + gap)
        .clamp(margin, screenSize.height - margin);
  }

  return showGeneralDialog<DateTimeRange>(
    context: context,
    barrierDismissible: true,
    barrierLabel: 'Close',
    useRootNavigator: true,
    barrierColor: Colors.transparent,
    pageBuilder: (ctx, animation, secondaryAnimation) {
      return Stack(
        children: [
          Positioned(
            left: left,
            top: top,
            child: _CompactDateRangeDialog(
              firstDate: DateTime(firstDate.year, firstDate.month, firstDate.day),
              lastDate: DateTime(lastDate.year, lastDate.month, lastDate.day),
              initialRange: initialRange,
              maxWidth: popupWidth,
            ),
          ),
        ],
      );
    },
    transitionBuilder: (ctx, animation, secondaryAnimation, child) {
      final curved = CurvedAnimation(parent: animation, curve: Curves.easeOutCubic);
      return FadeTransition(
        opacity: curved,
        child: child,
      );
    },
  );
}

enum _QuickPreset { today, yesterday, month, custom }

class _CompactDateRangeDialog extends StatefulWidget {
  const _CompactDateRangeDialog({
    required this.firstDate,
    required this.lastDate,
    this.initialRange,
    required this.maxWidth,
  });

  final DateTime firstDate;
  final DateTime lastDate;
  final DateTimeRange? initialRange;
  final double maxWidth;

  @override
  State<_CompactDateRangeDialog> createState() => _CompactDateRangeDialogState();
}

class _CompactDateRangeDialogState extends State<_CompactDateRangeDialog> {
  static const _muted = Color(0xFF64748B);
  Color get _primary => Theme.of(context).colorScheme.primary;
  Color get _primaryLight => _primary.withValues(alpha: 0.14);
  Color get _sidebarSelected => _primary;

  late DateTime _focusedMonth;
  DateTime? _start;
  DateTime? _end;
  _QuickPreset _preset = _QuickPreset.custom;

  final _headerFrom = DateFormat('EEE, dd MMM');
  final _headerMonth = DateFormat('MMMM yyyy');
  final _footerRange = DateFormat('dd/MM/yyyy');

  @override
  void initState() {
    super.initState();
    final ir = widget.initialRange;
    if (ir != null) {
      _start = DateTime(ir.start.year, ir.start.month, ir.start.day);
      _end = DateTime(ir.end.year, ir.end.month, ir.end.day);
      _focusedMonth = DateTime(_start!.year, _start!.month, 1);
      _preset = _QuickPreset.custom;
    } else {
      final now = DateTime.now();
      final n = DateTime(now.year, now.month, now.day);
      _focusedMonth = DateTime(n.year, n.month, 1);
      if (n.isBefore(widget.firstDate)) {
        _focusedMonth = DateTime(widget.firstDate.year, widget.firstDate.month, 1);
      } else if (n.isAfter(widget.lastDate)) {
        _focusedMonth = DateTime(widget.lastDate.year, widget.lastDate.month, 1);
      }
    }
  }

  bool _sameDay(DateTime a, DateTime b) =>
      a.year == b.year && a.month == b.month && a.day == b.day;

  DateTime _norm(DateTime d) => DateTime(d.year, d.month, d.day);

  bool _inSelectedRange(DateTime d) {
    if (_start == null) return false;
    final x = _norm(d);
    final s = _norm(_start!);
    final e = _norm(_end ?? _start!);
    return !x.isBefore(s) && !x.isAfter(e);
  }

  bool _isRangeStart(DateTime d) => _start != null && _sameDay(d, _start!);

  bool _isRangeEnd(DateTime d) {
    if (_start == null) return false;
    final end = _end ?? _start!;
    return _sameDay(d, end);
  }

  void _onDayTap(DateTime day) {
    final d = _norm(day);
    if (d.isBefore(widget.firstDate) || d.isAfter(widget.lastDate)) return;

    setState(() {
      _preset = _QuickPreset.custom;
      if (_start == null || (_start != null && _end != null)) {
        _start = d;
        _end = null;
      } else {
        if (d.isBefore(_start!)) {
          _end = _start;
          _start = d;
        } else {
          _end = d;
        }
      }
    });
  }

  void _clampToBounds(DateTime s, DateTime e) {
    var s0 = _norm(s);
    var e0 = _norm(e);
    if (s0.isBefore(widget.firstDate)) s0 = widget.firstDate;
    if (e0.isAfter(widget.lastDate)) e0 = widget.lastDate;
    if (s0.isAfter(e0)) e0 = s0;
    _start = s0;
    _end = e0;
  }

  void _setToday() {
    final n = DateTime.now();
    final d = DateTime(n.year, n.month, n.day);
    setState(() {
      _preset = _QuickPreset.today;
      _clampToBounds(d, d);
      _focusedMonth = DateTime(d.year, d.month, 1);
    });
  }

  void _setYesterday() {
    final n = DateTime.now().subtract(const Duration(days: 1));
    final d = DateTime(n.year, n.month, n.day);
    setState(() {
      _preset = _QuickPreset.yesterday;
      _clampToBounds(d, d);
      _focusedMonth = DateTime(d.year, d.month, 1);
    });
  }

  void _setThisMonth() {
    final n = DateTime.now();
    final start = DateTime(n.year, n.month, 1);
    final end = DateTime(n.year, n.month + 1, 0);
    setState(() {
      _preset = _QuickPreset.month;
      _clampToBounds(start, end);
      _focusedMonth = DateTime(n.year, n.month, 1);
    });
  }

  void _setCustomMode() {
    setState(() => _preset = _QuickPreset.custom);
  }

  void _clear() {
    setState(() {
      _start = null;
      _end = null;
      _preset = _QuickPreset.custom;
    });
  }

  bool get _canPrev {
    final lastOfPrevMonth = DateTime(_focusedMonth.year, _focusedMonth.month, 0);
    return !lastOfPrevMonth.isBefore(widget.firstDate);
  }

  /// Right panel shows month after [_focusedMonth]; allow next if that month's last day is not past [lastDate].
  bool get _canNext {
    final lastOfRightMonth = DateTime(_focusedMonth.year, _focusedMonth.month + 2, 0);
    return !lastOfRightMonth.isAfter(widget.lastDate);
  }

  void _prevMonth() {
    if (!_canPrev) return;
    setState(() {
      _focusedMonth = DateTime(_focusedMonth.year, _focusedMonth.month - 1, 1);
    });
  }

  void _nextMonth() {
    if (!_canNext) return;
    setState(() {
      _focusedMonth = DateTime(_focusedMonth.year, _focusedMonth.month + 1, 1);
    });
  }

  /// Sunday-first week grid cells for [month] (first day of month).
  List<DateTime> _calendarCellsForMonth(DateTime monthFirst) {
    final first = DateTime(monthFirst.year, monthFirst.month, 1);
    final daysInMonth = DateTime(monthFirst.year, monthFirst.month + 1, 0).day;
    final leading = first.weekday % 7;
    final cells = <DateTime>[];

    final prevEnd = DateTime(monthFirst.year, monthFirst.month, 0);
    for (int i = 0; i < leading; i++) {
      final dayNum = prevEnd.day - leading + i + 1;
      cells.add(DateTime(prevEnd.year, prevEnd.month, dayNum));
    }
    for (int d = 1; d <= daysInMonth; d++) {
      cells.add(DateTime(monthFirst.year, monthFirst.month, d));
    }
    var next = 1;
    while (cells.length % 7 != 0 || cells.length < 42) {
      cells.add(DateTime(monthFirst.year, monthFirst.month + 1, next));
      next++;
    }
    return cells;
  }

  void _apply() {
    if (_start == null) {
      Navigator.of(context).pop();
      return;
    }
    final end = _end ?? _start!;
    Navigator.of(context).pop(DateTimeRange(start: _start!, end: end));
  }

  Widget _dayCell(DateTime d, DateTime monthForGrid) {
    final inMonth = d.month == monthForGrid.month && d.year == monthForGrid.year;
    final disabled =
        d.isBefore(widget.firstDate) || d.isAfter(widget.lastDate);

    if (!inMonth) {
      return Center(
        child: Text(
          '${d.day}',
          style: GoogleFonts.inter(
            fontSize: 12,
            color: const Color(0xFF94A3B8),
            fontWeight: FontWeight.w500,
          ),
        ),
      );
    }

    final inRange = !disabled && _inSelectedRange(d);
    final isStart = !disabled && _isRangeStart(d);
    final isEnd = !disabled && _isRangeEnd(d);
    final span = _start != null &&
        _end != null &&
        !_sameDay(_start!, _end!);

    BorderRadius? bgRadius;
    if (inRange && span) {
      if (isStart) {
        bgRadius = const BorderRadius.horizontal(left: Radius.circular(20));
      } else if (isEnd) {
        bgRadius = const BorderRadius.horizontal(right: Radius.circular(20));
      } else {
        bgRadius = BorderRadius.zero;
      }
    }

    return GestureDetector(
      onTap: disabled ? null : () => _onDayTap(d),
      behavior: HitTestBehavior.opaque,
      child: Container(
        decoration: BoxDecoration(
          color: (inRange && span) ? _primaryLight : null,
          borderRadius: bgRadius,
        ),
        alignment: Alignment.center,
        child: Container(
          width: 32,
          height: 32,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: (isStart || isEnd) ? _primary : Colors.transparent,
            border: (isStart || isEnd)
                ? Border.all(color: Colors.white, width: 2)
                : null,
          ),
          child: Text(
            '${d.day}',
            style: GoogleFonts.inter(
              fontSize: 12,
              fontWeight:
                  (isStart || isEnd) ? FontWeight.w700 : FontWeight.w500,
              color: disabled
                  ? const Color(0xFFCBD5E1)
                  : (isStart || isEnd)
                      ? Colors.white
                      : const Color(0xFF0F172A),
            ),
          ),
        ),
      ),
    );
  }

  Widget _monthPanel(DateTime monthFirst) {
    final cells = _calendarCellsForMonth(monthFirst);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 6),
          child: Text(
            _headerMonth.format(monthFirst),
            textAlign: TextAlign.center,
            style: GoogleFonts.poppins(
              fontSize: 13,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF1E293B),
            ),
          ),
        ),
        Row(
          children: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
              .map(
                (w) => Expanded(
                  child: Center(
                    child: Text(
                      w,
                      style: GoogleFonts.inter(
                        fontSize: 10,
                        fontWeight: FontWeight.w600,
                        color: _primary,
                      ),
                    ),
                  ),
                ),
              )
              .toList(),
        ),
        const SizedBox(height: 4),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 7,
            mainAxisSpacing: 2,
            crossAxisSpacing: 2,
            childAspectRatio: 1.05,
          ),
          itemCount: cells.length,
          itemBuilder: (context, i) => _dayCell(cells[i], monthFirst),
        ),
      ],
    );
  }

  Widget _sidebarItem(String label, _QuickPreset preset, VoidCallback onTap) {
    final selected = _preset == preset;
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () {
          if (preset == _QuickPreset.custom) {
            _setCustomMode();
          } else {
            onTap();
          }
        },
        borderRadius: BorderRadius.circular(8),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
          decoration: BoxDecoration(
            color: selected ? _sidebarSelected : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            label,
            style: GoogleFonts.inter(
              fontSize: 13,
              fontWeight: selected ? FontWeight.w600 : FontWeight.w500,
              color: selected ? Colors.white : const Color(0xFF334155),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final leftMonth = _focusedMonth;
    final rightMonth = DateTime(_focusedMonth.year, _focusedMonth.month + 1, 1);

    return Material(
      color: Colors.transparent,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: const [
            BoxShadow(
              color: Color(0x26000000),
              blurRadius: 20,
              offset: Offset(0, 8),
            ),
          ],
        ),
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: widget.maxWidth,
          ),
          child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 148,
              color: const Color(0xFFF8FAFC),
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text(
                    'Quick select',
                    style: GoogleFonts.inter(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: _muted,
                    ),
                  ),
                  const SizedBox(height: 8),
                  _sidebarItem('Today', _QuickPreset.today, _setToday),
                  _sidebarItem('Yesterday', _QuickPreset.yesterday, _setYesterday),
                  _sidebarItem('Month', _QuickPreset.month, _setThisMonth),
                  _sidebarItem('Custom Range', _QuickPreset.custom, _setCustomMode),
                ],
              ),
            ),
            const VerticalDivider(width: 1, thickness: 1, color: Color(0xFFE2E8F0)),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.close, size: 22),
                          color: _muted,
                          onPressed: () => Navigator.of(context).pop(),
                          visualDensity: VisualDensity.compact,
                        ),
                      ],
                    ),
                    // Container(
                    //   decoration: BoxDecoration(
                    //     color: const Color(0xFFF8FAFC),
                    //     borderRadius: BorderRadius.circular(12),
                    //     border: Border.all(color: const Color(0xFFE2E8F0)),
                    //   ),
                    //  child: Row(
                       // children: [
                          // Expanded(
                          //   child: Padding(
                          //     padding: const EdgeInsets.symmetric(
                          //         vertical: 12, horizontal: 12),
                          //     child: Column(
                          //       crossAxisAlignment: CrossAxisAlignment.start,
                          //       children: [
                          //         Text(
                          //           'From',
                          //           style: GoogleFonts.inter(
                          //             fontSize: 11,
                          //             color: _muted,
                          //             fontWeight: FontWeight.w500,
                          //           ),
                          //         ),
                          //         const SizedBox(height: 4),
                          //         Text(
                          //           _start != null
                          //               ? _headerFrom.format(_start!)
                          //               : '—',
                          //           style: GoogleFonts.inter(
                          //             fontSize: 14,
                          //             fontWeight: FontWeight.w700,
                          //             color: const Color(0xFF0F172A),
                          //           ),
                          //         ),
                          //       ],
                          //     ),
                          //   ),
                          // ),
                          // Container(
                          //     width: 1,
                          //     height: 52,
                          //     color: const Color(0xFFE2E8F0)),
                          // Expanded(
                          //   child: Padding(
                          //     padding: const EdgeInsets.symmetric(
                          //         vertical: 12, horizontal: 12),
                          //     child: Column(
                          //       crossAxisAlignment: CrossAxisAlignment.start,
                          //       children: [
                          //         Text(
                          //           'To',
                          //           style: GoogleFonts.inter(
                          //             fontSize: 11,
                          //             color: _muted,
                          //             fontWeight: FontWeight.w500,
                          //           ),
                          //         ),
                          //         const SizedBox(height: 4),
                          //         Text(
                          //           _start != null
                          //               ? _headerFrom.format(_end ?? _start!)
                          //               : '—',
                          //           style: GoogleFonts.inter(
                          //             fontSize: 14,
                          //             fontWeight: FontWeight.w700,
                          //             color: const Color(0xFF0F172A),
                          //           ),
                          //         ),
                          //       ],
                          //     ),
                          //   ),
                          // ),
                       // ],
                     // ),
                    // ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        IconButton(
                          onPressed: _canPrev ? _prevMonth : null,
                          icon: const Icon(Icons.chevron_left),
                          color: _primary,
                        ),
                        Expanded(
                          child: Text(
                            '${_headerMonth.format(leftMonth)} – ${_headerMonth.format(rightMonth)}',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.poppins(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: const Color(0xFF1E293B),
                            ),
                          ),
                        ),
                        IconButton(
                          onPressed: _canNext ? _nextMonth : null,
                          icon: const Icon(Icons.chevron_right),
                          color: _primary,
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(child: _monthPanel(leftMonth)),
                        const SizedBox(width: 12),
                        Expanded(child: _monthPanel(rightMonth)),
                      ],
                    ),
                    const SizedBox(height: 12),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          vertical: 10, horizontal: 12),
                      decoration: BoxDecoration(
                        color: const Color(0xFFF1F5F9),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              _start != null
                                  ? '${_footerRange.format(_start!)} - ${_footerRange.format(_end ?? _start!)}'
                                  : 'Select a range',
                              style: GoogleFonts.inter(
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                                color: const Color(0xFF0F172A),
                              ),
                            ),
                          ),
                          TextButton(
                            onPressed: _clear,
                            child: Text(
                              'Clear',
                              style: GoogleFonts.poppins(
                                fontWeight: FontWeight.w600,
                                color: _muted,
                              ),
                            ),
                          ),
                          const SizedBox(width: 8),
                          FilledButton(
                            onPressed: _start != null ? _apply : null,
                            style: FilledButton.styleFrom(
                              backgroundColor: _sidebarSelected,
                              disabledBackgroundColor: const Color(0xFFCBD5E1),
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 20, vertical: 10),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                            ),
                            child: Text(
                              'Apply',
                              style: GoogleFonts.poppins(
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      ),
    );
  }
}
