import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

import 'responsive_section.dart';

/// 검색/필터 영역을 위한 공통 래퍼.
class FilterBar extends StatelessWidget {
  const FilterBar({
    super.key,
    required this.children,
    this.title = '검색 및 필터',
    this.actions,
    this.spacing = 16,
    this.runSpacing = 16,
    this.actionConfig,
    this.leading,
  });

  final List<Widget> children;
  final String? title;
  final List<Widget>? actions;
  final double spacing;
  final double runSpacing;
  final FilterBarActionConfig? actionConfig;
  final Widget? leading;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final computedActions = _resolveActions(context);
    final hasHeading =
        (title != null && title!.isNotEmpty) || computedActions.isNotEmpty;

    return ShadCard(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          if (hasHeading)
            Padding(
              padding: const EdgeInsets.only(bottom: 20),
              child: ResponsiveStackedRow(
                breakpoint: 560,
                gap: 12,
                leading: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (leading != null) ...[
                      leading!,
                      const SizedBox(width: 12),
                    ],
                    if (title != null && title!.isNotEmpty)
                      Flexible(child: Text(title!, style: theme.textTheme.h3)),
                  ],
                ),
                trailing: computedActions.isEmpty
                    ? const SizedBox.shrink()
                    : Align(
                        alignment: Alignment.centerRight,
                        child: Wrap(
                          spacing: 8,
                          runSpacing: 8,
                          alignment: WrapAlignment.end,
                          children: computedActions,
                        ),
                      ),
              ),
            ),
          Wrap(spacing: spacing, runSpacing: runSpacing, children: children),
        ],
      ),
    );
  }

  List<Widget> _resolveActions(BuildContext context) {
    final items = <Widget>[];
    final config = actionConfig;
    if (config != null) {
      final badge = _buildStatusBadge(context, config);
      if (badge != null) {
        items.add(badge);
      }
      items.add(
        ShadButton(
          key: config.applyKey,
          onPressed: config.canApply ? config.onApply : null,
          child: Text(config.applyLabel),
        ),
      );
      if (config.shouldShowReset) {
        items.add(
          ShadButton.ghost(
            key: config.resetKey,
            onPressed: config.canReset ? config.onReset : null,
            child: Text(config.resetLabel),
          ),
        );
      }
    }

    if (actions != null && actions!.isNotEmpty) {
      items.addAll(actions!);
    }

    return items;
  }

  Widget? _buildStatusBadge(
    BuildContext context,
    FilterBarActionConfig config,
  ) {
    final theme = ShadTheme.of(context);
    if (config.hasActiveFilters) {
      final badgeColor = theme.colorScheme.primary;
      return ShadBadge.outline(
        foregroundColor: badgeColor,
        backgroundColor: badgeColor.withValues(alpha: 0.08),
        hoverBackgroundColor: badgeColor.withValues(alpha: 0.12),
        shape: StadiumBorder(
          side: BorderSide(color: badgeColor.withValues(alpha: 0.4)),
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          child: Text('필터 적용됨', style: theme.textTheme.small),
        ),
      );
    }
    return null;
  }
}

/// 필터 적용/초기화 버튼 구성을 위한 상태 객체.
class FilterBarActionConfig {
  const FilterBarActionConfig({
    required this.onApply,
    required this.onReset,
    this.hasPendingChanges = false,
    this.hasActiveFilters = false,
    this.applyLabel = '검색 적용',
    this.resetLabel = '초기화',
    this.applyEnabled,
    this.resetEnabled,
    this.showReset,
    this.applyKey,
    this.resetKey,
  });

  final VoidCallback onApply;
  final VoidCallback onReset;
  final bool hasPendingChanges;
  final bool hasActiveFilters;
  final String applyLabel;
  final String resetLabel;
  final bool? applyEnabled;
  final bool? resetEnabled;
  final bool? showReset;
  final Key? applyKey;
  final Key? resetKey;

  /// 즉시 적용 가능한지 여부.
  bool get canApply => applyEnabled ?? hasPendingChanges;

  /// Reset 버튼을 노출할지 여부.
  bool get shouldShowReset =>
      showReset ?? (hasActiveFilters || hasPendingChanges);

  /// Reset 버튼이 활성화 가능한지 여부.
  bool get canReset => resetEnabled ?? shouldShowReset;
}
