import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:shadcn_ui/shadcn_ui.dart';

/// 페이지 이동용 <<, <, >, >> 버튼을 공통 스타일로 제공하는 위젯.
class SuperportPaginationControls extends StatelessWidget {
  const SuperportPaginationControls({
    super.key,
    required this.currentPage,
    required this.totalPages,
    this.onPageSelected,
    this.isBusy = false,
    this.size = ShadButtonSize.sm,
    this.spacing = 8,
    this.mainAxisSize = MainAxisSize.min,
  });

  /// 현재 선택된 페이지 번호(1-base).
  final int currentPage;

  /// 전체 페이지 수.
  final int totalPages;

  /// 페이지 변경 콜백. `null`이면 모든 버튼을 비활성화한다.
  final void Function(int page)? onPageSelected;

  /// 비동기 작업 중 여부. `true`면 버튼이 비활성화된다.
  final bool isBusy;

  /// 버튼 크기 옵션.
  final ShadButtonSize size;

  /// 버튼 간 간격.
  final double spacing;

  /// 내부 Row의 MainAxisSize.
  final MainAxisSize mainAxisSize;

  @override
  Widget build(BuildContext context) {
    final int safeTotal = totalPages <= 0 ? 1 : totalPages;
    final int safeCurrent = currentPage < 1
        ? 1
        : (currentPage > safeTotal ? safeTotal : currentPage);
    final bool canInteract = onPageSelected != null && !isBusy;
    final bool canGoPrev = canInteract && safeCurrent > 1;
    final bool canGoNext = canInteract && safeCurrent < safeTotal;

    return Row(
      mainAxisSize: mainAxisSize,
      children: _withSpacing([
        _buildButton(
          icon: lucide.LucideIcons.chevronsLeft,
          enabled: canGoPrev,
          onTap: () => onPageSelected?.call(1),
        ),
        _buildButton(
          icon: lucide.LucideIcons.chevronLeft,
          enabled: canGoPrev,
          onTap: () => onPageSelected?.call(safeCurrent - 1),
        ),
        _buildButton(
          icon: lucide.LucideIcons.chevronRight,
          enabled: canGoNext,
          onTap: () => onPageSelected?.call(safeCurrent + 1),
        ),
        _buildButton(
          icon: lucide.LucideIcons.chevronsRight,
          enabled: canGoNext,
          onTap: () => onPageSelected?.call(safeTotal),
        ),
      ]),
    );
  }

  List<Widget> _withSpacing(List<Widget> children) {
    final result = <Widget>[];
    for (var i = 0; i < children.length; i++) {
      if (i > 0) {
        result.add(SizedBox(width: spacing));
      }
      result.add(children[i]);
    }
    return result;
  }

  Widget _buildButton({
    required IconData icon,
    required bool enabled,
    required VoidCallback onTap,
  }) {
    return ShadButton.ghost(
      size: size,
      onPressed: enabled ? onTap : null,
      child: Icon(icon, size: 16),
    );
  }
}
