import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

/// Calendar selector widget for choosing dates.
///
/// Displays a week view with navigation buttons and date selection.
class CoverageCalendarSelector extends StatefulWidget {
  /// Creates a [CoverageCalendarSelector].
  const CoverageCalendarSelector({
    required this.selectedDate,
    required this.onDateSelected,
    super.key,
  });

  /// The currently selected date.
  final DateTime selectedDate;

  /// Callback when a date is selected.
  final ValueChanged<DateTime> onDateSelected;

  @override
  State<CoverageCalendarSelector> createState() =>
      _CoverageCalendarSelectorState();
}

class _CoverageCalendarSelectorState extends State<CoverageCalendarSelector> {
  late DateTime _today;

  @override
  void initState() {
    super.initState();
    _today = DateTime.now();
    _today = DateTime(_today.year, _today.month, _today.day);
  }

  /// Gets the list of calendar days to display (7 days centered on selected date).
  List<DateTime> _getCalendarDays() {
    final List<DateTime> days = <DateTime>[];
    final DateTime startDate =
        widget.selectedDate.subtract(const Duration(days: 3));
    for (int i = 0; i < 7; i++) {
      days.add(startDate.add(Duration(days: i)));
    }
    return days;
  }

  /// Navigates to the previous week.
  void _navigatePrevWeek() {
    widget.onDateSelected(
      widget.selectedDate.subtract(const Duration(days: 7)),
    );
  }

  /// Navigates to today's date.
  void _navigateToday() {
    final DateTime now = DateTime.now();
    widget.onDateSelected(DateTime(now.year, now.month, now.day));
  }

  /// Navigates to the next week.
  void _navigateNextWeek() {
    widget.onDateSelected(
      widget.selectedDate.add(const Duration(days: 7)),
    );
  }

  @override
  Widget build(BuildContext context) {
    final List<DateTime> calendarDays = _getCalendarDays();

    return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            _NavButton(
              text: '← Prev Week',
              onTap: _navigatePrevWeek,
            ),
            _NavButton(
              text: 'Today',
              onTap: _navigateToday,
            ),
            _NavButton(
              text: 'Next Week →',
              onTap: _navigateNextWeek,
            ),
          ],
        ),
        const SizedBox(height: UiConstants.space2),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: calendarDays.map((DateTime date) {
            final bool isSelected = date.year == widget.selectedDate.year &&
                date.month == widget.selectedDate.month &&
                date.day == widget.selectedDate.day;
            final bool isToday = date.year == _today.year &&
                date.month == _today.month &&
                date.day == _today.day;

            return GestureDetector(
              onTap: () => widget.onDateSelected(date),
              child: Container(
                width: UiConstants.space10 + UiConstants.space1,
                height: UiConstants.space14,
                decoration: BoxDecoration(
                  color: isSelected
                      ? UiColors.primaryForeground
                      : UiColors.primaryForeground.withOpacity(0.1),
                  borderRadius: UiConstants.radiusLg,
                  border: isToday && !isSelected
                      ? Border.all(
                          color: UiColors.primaryForeground,
                          width: 2,
                        )
                      : null,
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      date.day.toString().padLeft(2, '0'),
                      style: UiTypography.body1b.copyWith(
                        color: isSelected
                            ? UiColors.primary
                            : UiColors.primaryForeground,
                      ),
                    ),
                    Text(
                      DateFormat('E').format(date),
                      style: UiTypography.body4m.copyWith(
                        color: isSelected
                            ? UiColors.mutedForeground
                            : UiColors.primaryForeground.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}

/// Navigation button for calendar navigation.
class _NavButton extends StatelessWidget {
  /// Creates a [_NavButton].
  const _NavButton({
    required this.text,
    required this.onTap,
  });

  /// The button text.
  final String text;

  /// Callback when tapped.
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: UiConstants.space3,
          vertical: UiConstants.space1,
        ),
        decoration: BoxDecoration(
          color: UiColors.primaryForeground.withOpacity(0.2),
          borderRadius: UiConstants.radiusMd,
        ),
        child: Text(
          text,
          style: UiTypography.body3r.copyWith(
            color: UiColors.primaryForeground,
          ),
        ),
      ),
    );
  }
}
