import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class MonthPickerWidget extends StatefulWidget {
  const MonthPickerWidget({
    super.key,
    required this.selectedDate,
    required this.onDateSelected,
  });

  final DateTime selectedDate;
  final ValueChanged<DateTime>? onDateSelected;

  @override
  State<MonthPickerWidget> createState() => _MonthPickerWidgetState();
}

class _MonthPickerWidgetState extends State<MonthPickerWidget> {
  late int _currentYear;
  int? _selectedMonth;

  static const _monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];

  @override
  void initState() {
    super.initState();
    _currentYear = widget.selectedDate.year;
    _selectedMonth = widget.selectedDate.month - 1;
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: ColorsManager.whiteColors,
      child: Container(
        padding: const EdgeInsetsDirectional.all(20),
        width: 320,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildYearSelector(),
            _buildMonthsGrid(),
            const SizedBox(height: 20),
            Row(
              spacing: 12,
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                FilledButton(
                  onPressed: () => Navigator.pop(context),
                  style: FilledButton.styleFrom(
                    fixedSize: const Size(106, 40),
                    backgroundColor: const Color(0xFFEDF2F7),
                    padding: const EdgeInsetsDirectional.symmetric(
                      vertical: 10,
                      horizontal: 16,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Text(
                    'Cancel',
                    style: context.textTheme.titleSmall?.copyWith(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: ColorsManager.grey700,
                    ),
                  ),
                ),
                FilledButton(
                  onPressed: () {
                    Navigator.pop(context);
                    final date = DateTime(
                      _currentYear,
                      _selectedMonth! + 1,
                    );
                    widget.onDateSelected?.call(date);
                  },
                  style: FilledButton.styleFrom(
                    fixedSize: const Size(106, 40),
                    backgroundColor: ColorsManager.vividBlue.withValues(
                      alpha: 0.7,
                    ),
                    padding: const EdgeInsetsDirectional.symmetric(
                      vertical: 10,
                      horizontal: 16,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Text(
                    'Done',
                    style: context.textTheme.titleSmall?.copyWith(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: ColorsManager.whiteColors,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Row _buildYearSelector() {
    final currentYear = DateTime.now().year;
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          '$_currentYear',
          style: context.textTheme.titleSmall?.copyWith(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: ColorsManager.grey700,
          ),
        ),
        const Spacer(),
        IconButton(
          onPressed: () {
            setState(() {
              _currentYear = _currentYear - 1;
            });
          },
          icon: const Icon(
            Icons.chevron_left,
            color: ColorsManager.grey700,
          ),
        ),
        IconButton(
          onPressed: _currentYear < currentYear
              ? () {
                  setState(() {
                    _currentYear = _currentYear + 1;
                    // Clear selected month if it becomes invalid in the new year
                    if (_currentYear == currentYear &&
                        _selectedMonth != null &&
                        _selectedMonth! > DateTime.now().month - 1) {
                      _selectedMonth = null;
                    }
                  });
                }
              : null,
          icon: Icon(
            Icons.chevron_right,
            color: _currentYear < currentYear
                ? ColorsManager.grey700
                : ColorsManager.grey700.withValues(alpha: 0.3),
          ),
        ),
      ],
    );
  }

  Widget _buildMonthsGrid() {
    final currentDate = DateTime.now();
    final isCurrentYear = _currentYear == currentDate.year;

    return GridView.builder(
      shrinkWrap: true,
      itemCount: 12,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 2.5,
        mainAxisSpacing: 8,
        mainAxisExtent: 30,
      ),
      itemBuilder: (context, index) {
        final isSelected = _selectedMonth == index;
        final isFutureMonth = isCurrentYear && index > currentDate.month - 1;

        return InkWell(
          onTap: isFutureMonth ? null : () => setState(() => _selectedMonth = index),
          child: DecoratedBox(
            decoration: BoxDecoration(
              color: const Color(0xFFEDF2F7),
              borderRadius: BorderRadius.only(
                topLeft: index % 3 == 0 ? const Radius.circular(16) : Radius.zero,
                bottomLeft: index % 3 == 0 ? const Radius.circular(16) : Radius.zero,
                topRight: index % 3 == 2 ? const Radius.circular(16) : Radius.zero,
                bottomRight:
                    index % 3 == 2 ? const Radius.circular(16) : Radius.zero,
              ),
            ),
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: isSelected
                    ? ColorsManager.vividBlue.withValues(alpha: 0.7)
                    : isFutureMonth
                        ? ColorsManager.grey700.withValues(alpha: 0.1)
                        : const Color(0xFFEDF2F7),
                borderRadius:
                    isSelected ? BorderRadius.circular(15) : BorderRadius.zero,
              ),
              child: Text(
                _monthNames[index],
                style: context.textTheme.titleSmall?.copyWith(
                  fontSize: 12,
                  color: isSelected
                      ? ColorsManager.whiteColors
                      : isFutureMonth
                          ? ColorsManager.blackColor.withValues(alpha: 0.3)
                          : ColorsManager.blackColor.withValues(alpha: 0.8),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
